Twenty-six boxes
Count every letter with a list of 26 counters, one per letter. About 7 minutes.
A box for every letter
Scrabble players count their tiles: how many a's, how many e's. You can do the same for any string with a row of 26 boxes, one per letter, all starting at 0.
For each character, its position in the alphabet tells you exactly which box to add 1 to: a goes in box 0, b in box 1, z in box 25. No searching, no comparing. One walk and every letter is counted.
- char
- b
'b' is position 1, so box 1 goes up by one.
The counts come out in alphabetical order
After one walk, the first box holds the number of a's, the next the number of b's, and so on. Reading the boxes from left to right gives you every letter in alphabetical order, for free.
This only works for the 26 lowercase letters. A capital letter or a space would land outside the 26 boxes, so check what the problem promises about its input.
counts = [0] * 26
for ch in s:
counts[ord(ch) - ord("a")] += 1
return countsAfter counting "banana", what's in the box for the letter a?
- A3
- B1
- C6
Show the answer
3. "banana" has three a's.
Count every letter
You get a string of lowercase letters a to z. Return a list of 26 numbers: how many a's, how many b's, and so on up to z.
s = "banana" → [3, 1, 0, 0, …, 2, …, 0]
0 ≤ length ≤ 1,000,000 · only a to z