The idea
Each structure you know is fast at some operations and slow at others. A hash map finds a key in expected O(1) but has no order. A linked list moves a node anywhere in O(1) once you hold the node, but finding it is O(n). A heap gives the minimum in O(1) but cannot search. Combining two of them, with one pointing into the other, often gives a structure where every required operation is cheap.
The rule for every design below: write down the operations and their target costs first, then pick structures so that each operation is cheap in at least one of them, and keep an invariant that says how the two stay in sync.
The code in this lesson is pseudocode: these designs are combinations of the tested structures linked from each section, and of the built-ins listed at the end.
LRU cache: hash map + doubly linked list
Target: get(key) and put(key, value) in O(1); when full, put evicts the least recently used
entry.
- The doubly linked list keeps entries in recency order: most recent at the front, least recent at the back. Moving a node to the front or removing the back node is O(1).
- The hash map maps each key to its list node, so finding the node is expected O(1).
- Invariant: the map and the list contain exactly the same keys, and the list order is the order of last use.
Pseudocode
get(key):
node = map.get(key) # expected O(1)
if node is missing: return not found
list.move_to_front(node) # O(1): unlink, relink at the front
return node.value
put(key, value):
if key in map:
node = map[key]; node.value = value; list.move_to_front(node); return
if size == capacity:
old = list.remove_back() # O(1): least recently used
map.remove(old.key) # the node stores its key for exactly this step
node = list.push_front(key, value)
map[key] = node
Why doubly linked? Removing a node from the middle needs its predecessor; a singly linked list would have to search for it (see the singly linked list lesson). Why store the key in the node? Eviction starts from the list and must delete the matching map entry.
Built-ins. Java's LinkedHashMap constructed with accessOrder = true keeps exactly this
recency order, and overriding removeEldestEntry turns it into an LRU cache. Python's
OrderedDict has move_to_end and popitem(last=False), and functools.lru_cache memoizes
functions with this policy. C# and C++ have no ready-made LRU map: combine Dictionary<TKey, LinkedListNode<T>> with LinkedList<T>, or std::unordered_map<K, std::list<...>::iterator> with
std::list, whose iterators stay valid when nodes are moved with splice.
LFU (least frequently used) adds a frequency per key and a list per frequency; the minimum frequency is tracked so eviction stays O(1). Same principle, one more layer.
Randomized set: array + hash map
Target: insert, remove and getRandom (uniformly random element) all in expected O(1).
- An array gives O(1) random access, so
getRandompicks a random index. - A hash map from value to its array index makes membership and lookup expected O(1).
- Invariant:
map[array[i]] == ifor every index i.
Removing from the middle of an array is O(n) because of shifting (insert and delete in a fixed array). The trick is to swap the element with the last one, then pop the end:
Pseudocode
remove(x):
if x not in map: return false
i = map[x]
last = array[array.length - 1]
array[i] = last; map[last] = i # move the last element into the hole
array.pop_back(); map.remove(x)
return true
Order is not preserved, which is fine for a set. Removing the last element itself also works: it is
swapped with itself before being popped. Random number generators: Random.Shared.Next in C#,
random.randrange in Python, ThreadLocalRandom.current().nextInt in Java and
std::uniform_int_distribution with an engine in C++ (not rand() % n, which is biased).
Running median: two heaps
Target: add(x) in O(log n) and median() in O(1) over a stream.
- A max-heap
lowholds the smaller half of the values; a min-heaphighholds the larger half. - Invariant: every value in
low≤ every value inhigh, andlowhas the same number of elements ashighor exactly one more. - The median is the top of
low(odd count) or the average of both tops (even count).
Pseudocode
add(x):
if low is empty or x <= low.top(): low.push(x) else: high.push(x)
if low.size() > high.size() + 1: high.push(low.pop())
if high.size() > low.size(): low.push(high.pop())
Each add does at most three heap operations, so O(log n). Step through pushes and pops in the
binary heap lab above to see why each one costs O(log n). Watch the defaults: C#
PriorityQueue and Python heapq are min-heaps, Java PriorityQueue is a min-heap by natural
ordering, and C++ std::priority_queue is a max-heap by default (see the
heaps lesson). Averaging
two large integers can overflow in C#, Java and C++; compute a + (b - a) / 2 with care for the
sign, or use a wider type.
How to check a combined structure
- Write the invariant as code and assert it after every operation in your tests.
- Compare with a slow model: a plain list scanned for the LRU order, a list for the randomized set, a sorted list for the median. Run random operation sequences against both.
- Test the boundaries: capacity 1 for the cache, removing the only element of the set, the first two values of the median stream.
That is how every structure in this lab is tested in C#, Python, Java and C++; the problem pages show the brute-force reference beside each solution.
Summary
| Design | Structures | Invariant | Costs |
|---|---|---|---|
| LRU cache | hash map + doubly linked list | same keys; list in order of last use | get/put expected O(1) |
| Randomized set | array + hash map | map[array[i]] == i |
insert/remove/getRandom expected O(1) |
| Running median | max-heap + min-heap | low ≤ high; sizes differ by at most one | add O(log n), median O(1) |
The next step is the constraints-to-technique checklist, which decides when a custom structure is worth building at all.