Start learning free

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

Word Frequency in TypeScript: split and Count

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a dictionary where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in TypeScript, explained

    Problem overview

    The method wordFrequency receives a string, sentence, and returns an object that maps each word to the number of times it appears. The words are lowercase, separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

    For "the cat and the hat" the result is {"the": 2, "cat": 1, "and": 1, "hat": 1}. For "go go go" it is {"go": 3}: the same word three times is one key with the value 3. A sentence of one word, "hello", gives {"hello": 1}.

    Approach

    There are two jobs. First, turn the sentence into an array of words. Then count the words with the same pattern as counting letters: an object that starts empty, a pass over the array, and for each word either an increment or a first entry with the value 1.

    The first job is sentence.split(" "). It cuts the string at every space and returns the pieces as an array, so "the cat and the hat" becomes ["the", "cat", "and", "the", "hat"].

    Tracing "the cat and the hat": "the" is new and gets 1, then "cat" and "and" get 1 each. The second "the" is already a key, so its count goes from 1 to 2. "hat" is new. The final object is {"the": 2, "cat": 1, "and": 1, "hat": 1}. Words are only added to the object, never removed, so every word of the sentence ends up as a key.

    This is the same counting pattern as counting the letters of a word. The only change is what you loop over: the pieces from split instead of the characters of a string.

    Step by step

    1. Split the sentence. Store sentence.split(" ") in words, a string[].
    2. Create the dictionary. counts is an empty object of the type { [key: string]: number }.
    3. Loop over the words with for...of. Each word adds 1 to its own count.
    4. Known word. If word in counts, add 1 to counts[word].
    5. New word. Otherwise set counts[word] to 1. A missing key reads as undefined, and undefined + 1 is NaN, so a new word can't start by being incremented.
    6. Return counts after the loop.

    The solution in TypeScript

    class Solution {
        wordFrequency(sentence: string): { [key: string]: number } {
            const words: string[] = sentence.split(" ");
            const counts: { [key: string]: number } = {};
            for (let word of words) {
                if (word in counts) {
                    counts[word] += 1;
                } else {
                    counts[word] = 1;
                }
            }
            return counts;
        }
    }
    

    Details worth knowing:

    • split(" ") splits at every single space. That is exactly right when words are separated by single spaces, as here. With two spaces in a row, "a b".split(" ") gives ["a", "", "b"], and the empty string would be counted as a word. This lesson's sentences don't have double spaces.
    • Keys are strings. A word is already a string, so it is used as the key as written.
    • let word versus const word. The loop never reassigns word, so const would work too. Both pass the lesson's tests.
    • Plain objects have inherited keys. The in operator also finds keys an object gets from Object.prototype, such as toString and constructor. For the sentence "the toString", the code returns {"the":1,"toString":"function toString() { [native code] }1"}, because "toString" in counts is already true on an empty object. The lesson's words are ordinary lowercase words, so the tests don't hit this. For arbitrary text, a Map avoids the problem: counts.has(word) only sees keys you added.

    Edge cases and common mistakes

    • No first-time branch. Every count would be NaN.
    • Splitting on nothing. split("") cuts into single characters, which counts letters instead of words.
    • One word. "hello".split(" ") is ["hello"], and the result is {"hello": 1}.
    • Repeated word. "to be or not to be" gives {"to":2,"be":2,"or":1,"not":1}.

    Testing

    • "the cat and the hat" gives {"the":2,"cat":1,"and":1,"hat":1}.
    • "go go go" gives {"go":3}.
    • "hello" gives {"hello":1}.
    • "to be or not to be" gives {"to":2,"be":2,"or":1,"not":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