Social feed~10 min2s · 256 MBtarget O(n) time, O(1) spacestrings
A social app lets people write a caption under a photo. A fun feature highlights the letters that show up more than once in the caption, such as the a and the n in banana.
Captions use only the lowercase letters a to z. Your team lead wants to know how many different letters repeat in a caption.
Write repeated_letters(caption).
caption.Input: caption = "banana"
Output: 2The letter a appears 3 times, n appears 2 times and b appears once. So two different letters repeat.
| Letter | Times in banana |
Repeats? |
|---|---|---|
| a | 3 | yes |
| b | 1 | no |
| n | 2 | yes |
The answer is 2.
Input: caption = "abc"
Output: 0Every letter appears once, so no letter repeats.
Input: caption = "aaaa"
Output: 1The letter a appears four times. It is one letter, so the answer is 1.
1 ≤ length of caption ≤ 10^5caption has only the letters a to zScanning the whole caption once for each position reads about 10^5 x 10^5 = 10^10 letters. That is too slow.
There are only 26 possible letters, so a table of 26 counters is enough. One pass over the caption fills it, and 26 more steps read it.