Walk a sequence and count occurrences of each value in a hash map. Classic "get current count, add one, write back" loop.

Algorithm

Canonical input ["fig", "apple", "fig", "pear", "apple", "fig"] produces the final map {fig: 3, apple: 2, pear: 1}.

Basic Implementation

basic.ts
const words: string[] = ["fig", "apple", "fig", "pear", "apple", "fig"];
const count: Map<string, number> = new Map();
for (const word of words) {
    count.set(word, (count.get(word) ?? 0) + 1);
}
console.log(JSON.stringify(Object.fromEntries(count)));

Complexity

  • Time: O(n) average
  • Space: O(k) where k is the number of distinct keys

Implementation notes

  • TypeScript: const count: Map<string, number> = new Map(); with count.set(word, (count.get(word) ?? 0) + 1). The Map<string, number> annotation documents the key/value contract.
  • The replay renders the map as a list of key/value rows and animates the count increment on each frame.
get-or-default `count.get(word) ?? 0` returns the current count or `0`. Adding one and writing back via `count.set` is the canonical pattern.