Start learning free

LESSON 224 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Letter Count in JavaScript: Count Characters with an Object

Practice Read the full explanation

Given a string word, return a dictionary that maps each letter of word to the number of times it appears in word.

Every letter of word is a key, and its value is how many times that letter appears. The order of the entries doesn't matter.

 

Example 1:

Input: word = "banana"
Output: {"b": 1, "a": 3, "n": 2}
Explanation: "b" appears once, "a" three times and "n" twice.

Example 2:

Input: word = "hello"
Output: {"h": 1, "e": 1, "l": 2, "o": 1}
Explanation: "l" appears twice; every other letter appears once.

Example 3:

Input: word = "a"
Output: {"a": 1}
Explanation: A single letter appears once.

 

Constraints:

  • word has at least one letter.
  • word is made of lowercase English letters, a to z.
  • Only the letters of word are keys: a letter that doesn't appear has no entry.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in JavaScript, explained

    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

    1. Create an empty object named counts with {}. Declare it with const: the variable keeps pointing at the same object, and adding keys or changing their values is still allowed.
    2. Loop over the string with for...of. A string is iterable, so the loop variable letter takes each character in turn.
    3. Check for an existing key with letter in counts. If it is there, counts[letter] += 1.
    4. Handle the first sighting in the else branch: counts[letter] = 1.
    5. Return counts after 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 variable letter as the key. counts.letter would use the literal key "letter" instead.
    • Missing keys read as undefined. counts["z"] on an object without a "z" entry gives undefined, and undefined + 1 is NaN. That is why the first sighting must set the value to 1 instead of adding to it.
    • The in operator 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...of on a string visits characters, while for...in would visit index positions as strings. Use of here.

    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 only counts[letter] += 1 turns the first count into NaN.
    • 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}.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free