DSA Factory
Free Strings lessonsStrings · Stage 1 · Counting characters · Step 1

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.

The letter picks the box: no searching needed.
Counting "banana" (boxes a to n shown; o to z stay 0)
abcdefghijklmn
0
1
0
0
0
0
0
0
0
0
0
0
0
0
char
b

'b' is position 1, so box 1 goes up by one.

Move 1 of 6

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.

Only a to z: anything else lands outside the boxes.
In code
counts = [0] * 26
for ch in s:
    counts[ord(ch) - ord("a")] += 1
return counts
Quick check

After counting "banana", what's in the box for the letter a?

  1. A3
  2. B1
  3. C6
Show the answer

3. "banana" has three a's.

Your problem

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.

Example
s = "banana" → [3, 1, 0, 0, …, 2, …, 0]

0 ≤ length ≤ 1,000,000 · only a to z

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve