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.js
const words = ["fig", "apple", "fig", "pear", "apple", "fig"];
const count = 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

  • JavaScript: const count = new Map(); with count.set(word, (count.get(word) || 0) + 1). A plain object literal works too, but Map preserves insertion order explicitly.
  • 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.