Hashing & Frequency Maps

A hash map remembers what you've already read, so asking for a value, a partner or a group takes one lookup instead of a scan.

Two Sum: find the two numbers that add up to the target

StopTrace
numstarget

nums

  1. 30
  2. 81
  3. 42
  4. 13
  5. 64

seen (map)

  • empty

1/16seen starts empty: no number has been read yet.

Typical cost O(n) time, O(n) space (amortized O(1) per op)Full lesson: Two Sum →

When to reach for it

  • You keep asking whether you've seen something before.
  • Each item needs a partner: the number that completes a sum, the letter that cancels a count.
  • Items belong together when they share a key, like their letter counts.
  • The brute force is a nested loop that rescans what it already read.

What stays true

Each number is stored only after its own lookup, so seen never holds the current number or anything after it. A repeat overwrites its index, so a match pairs with the latest copy.

The map holds exactly what's been read

StopTrace
Invariantseen maps every number before i to its latest index, and nothing else.✓ Holds

nums

  1. 40
  2. 11
  3. 42
  4. 63

seen (map)

  • empty
target10

1/13seen starts empty: no number has been read yet.

Break it

Each input here has tripped up a version of this code. The stage runs the one that gets it right.

Storing 3 before its lookup finds it at once and answers [0, 0]. Looking up first finds 2 + 4.

Two Sum on the inputs that trip it up

StopTrace

nums

  1. 30
  2. 21
  3. 42

seen (map)

  • empty
target6

1/10seen starts empty: no number has been read yet.

Answer[1, 2]Steps10

Variants

Contains duplicate

9/9
StopTrace

nums

  1. 40
  2. 11
  3. 72
  4. i4✓3

seen (set)

4 ✓ in seen

  • 4✓
  • 1
  • 7
  • CH1 i

A set answers one question: has this number come up before?

Step through it →

Valid anagram

15/15
StopTrace

s

  1. l0
  2. i1
  3. s2
  4. t3
  5. e4
  6. n5

t

  1. s0
  2. i1
  3. l2
  4. e3
  5. n4
  6. t5

count (map)

  • e:0✓
  • i:0✓
  • l:0✓
  • n:0✓
  • s:0✓
  • t:0✓

Every other key: 0

len(s)6len(t)6

Count up for one string and down for the other. Anagrams end at all zeros.

Step through it →

Group anagrams

14/14
StopTrace

strs

  1. eat0
  2. tea1
  3. tan2
  4. ate3
  5. nat4
  6. bat5

groups (map)

  • a1 e1 t1:[eat, tea, ate]✓
  • a1 n1 t1:[tan, nat]✓
  • a1 b1 t1:[bat]✓

Key each word by its letter counts, and the groups form on their own.

Step through it →

Longest consecutive sequence

20/20
StopTrace

values (set)

  • 100
  • 4✓
  • 200
  • 1✓
  • 3✓
  • 2✓
best4

Walk a run only from its first number, the one whose left neighbor is missing.

Step through it →

The code

The same algorithm in plain Python. The lit line is the one the current frame came from.

Two Sum: find the two numbers that add up to the target

StopTrace

nums

  1. 30
  2. 81
  3. 42
  4. 13
  5. 64

seen (map)

  • empty
target10

1/16seen starts empty: no number has been read yet.

two_sum.py
def two_sum(nums, target):    seen = {}    for i, num in enumerate(nums):        complement = target - num        if complement in seen:            return [seen[complement], i]        seen[num] = i    return []

Drill it

In the wild

Apps & feedsSpotify shuffleWhy does a truly random shuffle play the same artist twice in a row?Fisher–Yates against a shuffle that spreads each artist out, run thousands of times and counted.Run it →Everyday techBloom filtersHow can a filter say “definitely not” without keeping the list?k hashes set bits in an array of m; a lookup reads them back. Then 10,000 lookups measure the false positives.Run it →Apps & feedsShazamHow does Shazam name a song from five seconds of noisy sound?A spectrogram's peaks, paired into hashes and matched by when they line up, as in Shazam's 2003 paper.Run it →ElectionsRanked-choice votingHow can the candidate who leads the first count still lose?Instant-runoff counting, round by round: the last-place candidate is out and their ballots move on.Run it →AIChatGPTHow does ChatGPT decide which word comes next?Next-word odds from word-pair counts in Alice in Wonderland, reshaped by temperature, cut by top-p and sampled one word at a time.Run it →AIChatGPT tokensWhy can't ChatGPT count the r's in strawberry?Byte-pair encoding: 1,000 merges learned from Alice in Wonderland, applied in order to your text, and the token numbers the model would see.Run it →GamesWordleWhy is one of my two E's gray when the answer has an E?Wordle's two-pass coloring, letter by letter, then a solver that scores every guess by expected information.Run it →Why it happensShared birthdaysHow many people do you need for two to share a birthday?Rooms filled one person at a time until two share a birthday, then 1,000 rooms measured against the exact odds and the pigeonhole limit.Run it →