Start learning free

LESSON 227 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Letter Count in TypeScript: Counting 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

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Letter Count in TypeScript, explained

    Problem overview

    The method letterCount receives a string, word, and returns a dictionary: an object whose keys are the letters of the word and whose values say how many times each letter appears. The order of the entries doesn't matter, and a letter that doesn't appear has no entry.

    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}. The word has at least one letter and only lowercase letters.

    Approach

    This is the basic counting pattern: an object that starts empty, and one pass over the input. For each letter there are two cases:

    • the letter is already a key, so its count goes up by one;
    • the letter is new, so it gets a key with the count 1.

    Tracing "banana": "b" is new, so counts becomes {"b": 1}. "a" is new: {"b": 1, "a": 1}. "n" is new: {"b": 1, "a": 1, "n": 1}. Then "a" is already there and becomes 2, "n" becomes 2, and the last "a" becomes 3. Each letter is handled once, so the work grows in step with the length of the word.

    Step by step

    1. Create the empty object. Declare counts with const and the type { [key: string]: number }, which says: any string key, with a number as its value. const stops you from pointing counts at another object, but you can still add keys and change values.
    2. Loop over the letters. A for...of loop over a string visits its characters one at a time, each as a string of length 1.
    3. Existing letter. If letter in counts is true, add 1 to counts[letter] with +=.
    4. New letter. In the else branch, set counts[letter] to 1.
    5. Return after the loop. Now every letter of word is a key.

    The solution in TypeScript

    class Solution {
        letterCount(word: string): { [key: string]: number } {
            const counts: { [key: string]: number } = {};
            for (const letter of word) {
                if (letter in counts) {
                    counts[letter] += 1;
                } else {
                    counts[letter] = 1;
                }
            }
            return counts;
        }
    }
    

    Details worth knowing:

    • The in operator checks whether an object has a key. "a" in counts is true once "a" has been counted.
    • Why the else matters. Reading a missing key from an object gives undefined, and undefined + 1 is NaN, not 1. That is why a new letter is set to 1 directly instead of being incremented.
    • The index signature is a compile-time promise. { [key: string]: number } is erased when TypeScript compiles to JavaScript. At run time counts is an ordinary object.
    • Entry order. The entries come out in the order the letters first appeared, so "banana" prints as {"b":1,"a":3,"n":2}. The lesson doesn't depend on that order.

    Edge cases and common mistakes

    • Skipping the first-time case. Without the else, every count would be NaN, because the first += adds 1 to undefined.
    • Starting counts at 0 for every letter of the alphabet. That would add keys for letters that don't appear, but only the letters of word may be keys.
    • A one-letter word. "a" goes straight to the else and returns {"a": 1}.
    • Returning inside the loop. Only the first letter would be counted.

    Testing

    • "banana" gives {"b":1,"a":3,"n":2}.
    • "hello" gives {"h":1,"e":1,"l":2,"o":1}.
    • "a" gives {"a":1}.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free