Problem overview
The method letterCount receives a string, word, and returns a dictionary that maps each letter of the word to the number of times it appears. Only letters that occur in the word get an entry, and the order of the entries doesn't matter.
For "banana" the result is {'b': 1, 'a': 3, 'n': 2}. For "hello" it is {'h': 1, 'e': 1, 'l': 2, 'o': 1}, and for "a" it is {'a': 1}.
Approach: a counting dictionary
A dictionary stores key-value pairs, so it is the natural tool for "how many of each". Each letter is a key, and its value is how many times that letter has been seen so far. The loop visits the letters one at a time. A letter that is already a key gets its count raised by one. A letter that is new gets an entry that starts at 1.
The two cases have to be handled separately because reading a key that isn't in a dictionary is an error, as the next section shows.
Step by step
- Create an empty dictionary named
counts. Nothing has been counted yet. - Loop over the letters with
for letter in word. Aforloop over a string visits its characters one by one, just as a loop over a list visits its items. - Check whether the letter is already a key with
if letter in counts. If it is, add 1 withcounts[letter] += 1. - Handle the first sighting in an
else:counts[letter] = 1. Assigning to a key that doesn't exist yet creates it. - Return
countsafter the loop.
Watching the dictionary grow
For "banana", the dictionary after each letter looks like this:
| letter | counts afterwards |
|---|---|
| b | {'b': 1} |
| a | {'b': 1, 'a': 1} |
| n | {'b': 1, 'a': 1, 'n': 1} |
| a | {'b': 1, 'a': 2, 'n': 1} |
| n | {'b': 1, 'a': 2, 'n': 2} |
| a | {'b': 1, 'a': 3, 'n': 2} |
The solution in Python
class Solution:
def letterCount(self, word: str) -> Dict[str, int]:
counts = {}
for letter in word:
if letter in counts:
counts[letter] += 1
else:
counts[letter] = 1
return counts
Details worth knowing:
inchecks keys.letter in countsasks whetherletteris a key of the dictionary. It never looks at the values.- A missing key raises
KeyError. Runningcounts["x"] += 1on an empty dictionary stops withKeyError: 'x', because+=has to read the old value first. That is why the first sighting needs its own branch. - Dictionaries keep insertion order. The result lists letters in the order they first appeared. The lesson doesn't depend on that order, but it explains why the printed dictionaries above start with
'b'for "banana". - Shorter forms exist.
counts[letter] = counts.get(letter, 0) + 1replaces theifandelse, andcollections.Counter(word)does the whole job. Writing the branches by hand first makes both easier to understand.
Edge cases and common mistakes
- Adding to a missing key. Skipping the
elsebranch, or writing onlycounts[letter] += 1, raises aKeyErroron the first letter. - Starting every count at 0 instead of 1. If the first sighting sets the value to 0, every count ends one too low.
- Returning inside the loop. The function would give back a dictionary with only the first letter.
- Single letter.
"a"gives{'a': 1}: the loop runs once and only theelsebranch is used.
Testing
"banana"gives{'b': 1, 'a': 3, 'n': 2}."hello"gives{'h': 1, 'e': 1, 'l': 2, 'o': 1}."a"gives{'a': 1}.
