3.3.10 · D3Hashing

Worked examples — Applications — frequency counting, two-sum problem, caching (LRU)

2,278 words10 min readBack to topic

This page is a stress test. We take the three tools from the parent note — frequency counting, Two-Sum-style complement lookups, and the LRU cache — and throw every awkward input at them: empty lists, duplicates, negatives, self-pairs, "no answer exists", a cache that is full, a cache of capacity zero, and an exam-style twist. If you can follow every cell below, no interviewer input can surprise you.


The scenario matrix

Every problem in this topic is really one of the cells below. A "cell" is a class of input that behaves differently from the others — so if we solve one example per cell, we have solved the whole topic.

# Tool Case class What makes it special
C1 Frequency Normal input, repeats The everyday histogram
C2 Frequency Empty / single input (degenerate) Loop runs 0 or 1 times
C3 Frequency Order matters (first-unique) Needs a second pass
C4 Two-Sum Answer exists early Complement found before scan ends
C5 Two-Sum No answer exists Must return "nothing" cleanly
C6 Two-Sum Negatives + duplicates Complement can be negative / equal to x
C7 Two-Sum Self-pair trap (target = 2x) Must not use one element twice
C8 LRU Fill, touch, evict The classic recency dance
C9 LRU Capacity = 1 / 0 (limiting) Edge of the definition
C10 LRU + Two-Sum Real-world word problem / exam twist Combine two tools

Below, ten worked examples cover all ten cells.


Frequency counting


Two-Sum

Figure — Applications — frequency counting, two-sum problem, caching (LRU)

LRU Cache

Figure — Applications — frequency counting, two-sum problem, caching (LRU)

Real-world twist (combining tools)


Recall Self-test (cover the answers)

Which cell has the empty-input frequency map? ::: C2 — the loop runs zero times, map stays {}. In Two-Sum, why store the value after checking the complement? ::: To stop an element pairing with itself (Cell C7, [3,3], target 6). With LRU capacity 2, after put(1),put(2),get(1),put(3) — who is evicted? ::: Key 2, because get(1) made 1 the most-recent, leaving 2 at the back. What does Two-Sum return when no pair exists? ::: None — the loop ends without a match (Cell C5). Why does LRU need a Doubly Linked List not a singly linked one? ::: A doubly linked node stores prev, so unlinking is ; a singly linked list would need an search for the predecessor.

Related: Hash Functions · Collision Resolution (Chaining vs Open Addressing) · Sliding Window · Caching Strategies.