Problem overview
The method letterCount(word) receives a string of lowercase letters and returns an object, used as a dictionary, that maps each letter to the number of times it appears. Only letters that occur in the word get an entry.
For "banana" the result is {"b": 1, "a": 3, "n": 2}: one "b", three "a" and two "n". The order of the entries doesn't matter.
Approach
This is the counting dictionary pattern. Go through the letters one at a time. For each letter, ask whether it already has an entry. If it does, add 1 to its count. If not, this is its first appearance, so create the entry with the value 1. After the last letter, the object holds every count.
One pass over the word is enough, and no letter needs to be looked at twice. You never have to know in advance which letters will show up, because new keys are created as they appear.
Step by step
- Create an empty object named
countswith{}. Declare it withconst: the variable keeps pointing at the same object, and adding keys or changing their values is still allowed. - Loop over the string with
for...of. A string is iterable, so the loop variablelettertakes each character in turn. - Check for an existing key with
letter in counts. If it is there,counts[letter] += 1. - Handle the first sighting in the
elsebranch:counts[letter] = 1. - Return
countsafter the loop.
The solution in JavaScript
class Solution {
letterCount(word) {
const counts = {};
for (let letter of word) {
if (letter in counts) {
counts[letter] += 1;
} else {
counts[letter] = 1;
}
}
return counts;
}
}
The details that matter in JavaScript:
- Square brackets for dynamic keys.
counts[letter]uses the value of the variableletteras the key.counts.letterwould use the literal key "letter" instead. - Missing keys read as
undefined.counts["z"]on an object without a "z" entry givesundefined, andundefined + 1isNaN. That is why the first sighting must set the value to 1 instead of adding to it. - The
inoperator checks whether a key exists, whatever its value. It also finds keys inherited from the object's prototype, such as"toString", which is harmless for single letters because no inherited name is one character long. for...ofon a string visits characters, whilefor...inwould visit index positions as strings. Useofhere.
Tracing the examples
For "banana" the object changes like this: "b" is new, so {b: 1}. "a" is new, so {b: 1, a: 1}. "n" is new, giving {b: 1, a: 1, n: 1}. The next "a" and "n" increase their counts to 2, and the last "a" makes it 3. The final object has b: 1, a: 3, n: 2, and the entries appear in the order the letters first showed up.
For "hello" the result is {h: 1, e: 1, l: 2, o: 1}, and for "a" it is {a: 1}.
Complexity
Time: O(n), where n is the length of the word. The loop runs once per character, and each membership check, read and write on an object takes constant time on average.
Space: O(k), where k is the number of different letters. The object holds one entry per distinct letter, and for lowercase English letters k can never exceed 26, so the extra space is effectively constant.
Reading the result
Once you have the object, reading it is just as direct. For the counts of "banana", counts["a"] is 3, and counts["z"] is undefined because "z" never appeared. Object.keys(counts).length is 3, the number of different letters. To visit every pair, use Object.entries(counts), which gives [["b", 1], ["a", 3], ["n", 2]], and unpack each pair in a loop with for (const [letter, count] of Object.entries(counts)). That loop prints b 1, a 3 and n 2, one per line.
A letter-count object is a building block for many small problems: checking whether two words are anagrams, finding the most common character, or spotting the first letter that appears only once. All of them start with this same loop and then ask a question of the finished object.
Other ways to write it
The if/else version spells out both cases, which is why the lesson uses it. A common shorter form handles both cases on one line by supplying a default for a missing key:
counts[letter] = (counts[letter] ?? 0) + 1;
The ?? operator gives its right side when the left side is undefined or null, so a first sighting computes 0 + 1. On "banana" this produces the same object, {b: 1, a: 3, n: 2}. A Map works the same way with get and set and prints as Map(3) {'b' => 1, 'a' => 3, 'n' => 2}. The lesson asks for an object, so return an object. If you do build a Map, Object.fromEntries(map) converts it to a plain object.
Edge cases and common mistakes
- Skipping the
else. Writing onlycounts[letter] += 1turns the first count intoNaN. - Starting every letter at 0 in advance. That would add keys for letters that never appear, but the task says absent letters have no entry.
- Counting the same letter twice in a row. The word
"aa"gives{a: 2}, with the first pass creating the key and the second adding to it. - Printing order. Don't rely on the order of keys in the output. For letters, JavaScript keeps insertion order, but the tests accept any order.
Testing
"banana"gives{b: 1, a: 3, n: 2}."hello"gives{h: 1, e: 1, l: 2, o: 1}."a"gives{a: 1}."ab"gives{a: 1, b: 1}.
