Designing Data Structures

How to build a structure with fast operations by combining a hash map, list, stack or heap, worked through a min-stack and an LRU cache.

19 minLesson 3 of 3
On this page
  1. How to approach a design problem
  2. A stack that returns its minimum in O(1)
  3. An LRU cache
  4. Other combinations of structures
  5. Pitfalls
  6. In the interview
  7. What to practise next

A design problem asks you to build a structure that supports a given set of operations, each within a stated time, usually O(1) or O(log n). No single built-in structure is fast at every operation, so the solution is to combine two or more of them and keep them consistent. You reach for this technique when a problem says "design a class" and lists methods with required complexities.

An LRU cache shows why. It must find an entry by key, mark it as just used, and find the least recently used entry, all in O(1). A hash map finds a key quickly but keeps no usage order, and a list keeps an order but cannot find a key without scanning. Combining the two gives all three operations.

How to approach a design problem

The same four steps work for most design questions.

  1. List the operations and the time each one needs. The required complexities usually decide the design.
  2. Pick a structure that makes each operation cheap. A hash map gives lookup by key, a stack gives last-in first-out access, a heap gives the smallest or largest item, and a doubly linked list gives order with removal from the middle.
  3. Decide how the parts refer to each other. Usually one structure stores pointers or indexes into another, so that no operation has to search.
  4. State the invariant and check every method against it. The invariant is the rule that must be true after every call, such as "the map holds exactly the keys that are in the list".

A stack that returns its minimum in O(1)

The task is a stack with push, pop, top and getMin, where every operation is O(1). A plain stack answers getMin by scanning all of its items, which is O(n).

Keeping a single variable with the smallest value makes push easy, but after you pop that value the variable is wrong, and finding the next smallest needs a scan. The variable has lost the history of earlier minimums.

The fix is to keep that history in a second stack. When a value is pushed, the second stack receives the smallest value in the whole stack at that moment. The two stacks always have the same height, and the top of the second one is the current minimum. Popping both stacks restores the previous minimum automatically.

Min-stack: push 5, 3, 7, 2, then pop twiceUse the arrows or ← → keys
  1. values
    05
    mins
    05
    getMin
    5

    1Push 5. It is the only value, so the minimum is 5.

  2. values
    05
    13
    mins
    05
    13
    getMin
    3

    2Push 3. It is smaller than 5, so mins gets a 3.

  3. values
    05
    13
    27
    mins
    05
    13
    23
    getMin
    3

    3Push 7. The minimum is still 3, so mins gets another 3 and both stacks stay the same height.

  4. values
    05
    13
    27
    32
    mins
    05
    13
    23
    32
    getMin
    2

    4Push 2. This is a new minimum, so mins gets a 2.

  5. values
    05
    13
    27
    mins
    05
    13
    23
    popped
    2
    getMin
    3

    5Pop. The 2 leaves both stacks, and the top of mins is now 3, which is the minimum of 5, 3 and 7. No scan was needed.

  6. values
    05
    13
    mins
    05
    13
    popped
    7
    getMin
    3

    6Pop the 7. The minimum is still 3. Every operation touched only the tops of the stacks, so each one took O(1).

1 / 6
Min-stack
class MinStack {
  constructor() {
    this.values = [];
    this.mins = []; // mins[i] = smallest of values[0..i]
  }
  push(x) {
    const currentMin = this.mins.length ? this.mins[this.mins.length - 1] : x;
    this.values.push(x);
    this.mins.push(Math.min(x, currentMin));
  }
  pop() {
    this.mins.pop();
    return this.values.pop();
  }
  top() { return this.values[this.values.length - 1]; }
  getMin() { return this.mins[this.mins.length - 1]; }
}
class MinStack:
    def __init__(self):
        self.values = []
        self.mins = []  # mins[i] = smallest of values[0..i]
 
    def push(self, x):
        current_min = self.mins[-1] if self.mins else x
        self.values.append(x)
        self.mins.append(min(x, current_min))
 
    def pop(self):
        self.mins.pop()
        return self.values.pop()
 
    def top(self):
        return self.values[-1]
 
    def get_min(self):
        return self.mins[-1]

The invariant is that mins[i] is the smallest of values[0..i] and both stacks have the same height. push and pop each change both stacks by exactly one item, so the invariant holds after every call.

An LRU cache

An LRU cache (least recently used) stores at most capacity key-value pairs. get(key) returns the value and counts as a use of that key. put(key, value) adds a pair or replaces the value of an existing one, and if the cache is full it first removes the pair that was used longest ago. Both operations must be O(1).

Each requirement points to a structure.

  • Finding an entry by key needs a hash map.
  • Keeping entries in order of use, moving any entry to the front and removing the oldest from the back needs a doubly linked list. If you hold a node, its prev and next pointers let you unlink it in O(1).
  • The two are connected by making the map store key → node instead of key → value. Then get reaches the node in one lookup. Each node also stores its own key, so that when the oldest node is removed you know which map entry to delete.
hash map mail chat maps head mail chat maps tail newest oldest
The hash map points straight at the nodes of a doubly linked list, which is ordered from the most recently used to the least recently used.

The list has two dummy nodes, head and tail, that are never removed. Every real node therefore has a neighbour on each side, and the code never has to handle an empty list or a node at the end as a special case.

LRU cache with capacity 3Use the arrows or ← → keys
  1. newest to oldest
    0mail
    null
    map keys
    mail
    size
    1

    1put("mail"). A new node goes at the front of the list, and the map stores mail → node.

  2. newest to oldest
    0maps
    1mail
    null
    map keys
    mail, maps
    size
    2

    2put("maps"). The new node goes at the front.

  3. newest to oldest
    0chat
    1maps
    2mail
    null
    map keys
    mail, maps, chat
    size
    3

    3put("chat"). The cache is now full, with mail as the oldest entry.

  4. newest to oldest
    0mail
    1chat
    2maps
    null
    map keys
    mail, maps, chat
    size
    3
    returned
    mail's value

    4get("mail"). The map finds mail's node directly. A get counts as a use, so the node moves from the back to the front with a few pointer changes.

  5. newest to oldest
    0mail
    1chat
    null
    map keys
    mail, chat
    size
    2
    evicted
    maps

    5put("news") on a full cache. The node just before tail is maps, the least recently used. It is unlinked, and its stored key is used to delete its map entry.

  6. newest to oldest
    0news
    1mail
    2chat
    null
    map keys
    mail, chat, news
    size
    3

    6The news node is added at the front. Without the earlier get, mail would have been evicted instead of maps. Every step took O(1).

1 / 6
LRU cache
class LRUCache {
  constructor(capacity) { // capacity >= 1
    this.capacity = capacity;
    this.map = new Map(); // key -> node
    this.head = { next: null }; // sentinel on the newest side
    this.tail = { prev: this.head }; // sentinel on the oldest side
    this.head.next = this.tail;
  }
  unlink(node) {
    node.prev.next = node.next;
    node.next.prev = node.prev;
  }
  addFront(node) {
    node.prev = this.head;
    node.next = this.head.next;
    this.head.next.prev = node;
    this.head.next = node;
  }
  get(key) {
    const node = this.map.get(key);
    if (node === undefined) return null;
    this.unlink(node); // a get counts as a use
    this.addFront(node);
    return node.value;
  }
  put(key, value) {
    if (this.map.has(key)) {
      this.unlink(this.map.get(key));
    } else if (this.map.size === this.capacity) {
      const oldest = this.tail.prev;
      this.unlink(oldest);
      this.map.delete(oldest.key); // why the node stores its key
    }
    const node = { key, value };
    this.addFront(node);
    this.map.set(key, node);
  }
}
class Node:
    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None
 
class LRUCache:
    def __init__(self, capacity):  # capacity >= 1
        self.capacity = capacity
        self.map = {}  # key -> node
        self.head, self.tail = Node(), Node()  # sentinels
        self.head.next, self.tail.prev = self.tail, self.head
 
    def _unlink(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
 
    def _add_front(self, node):
        node.prev, node.next = self.head, self.head.next
        self.head.next.prev = node
        self.head.next = node
 
    def get(self, key):
        node = self.map.get(key)
        if node is None:
            return None
        self._unlink(node)  # a get counts as a use
        self._add_front(node)
        return node.value
 
    def put(self, key, value):
        if key in self.map:
            self._unlink(self.map[key])
        elif len(self.map) == self.capacity:
            oldest = self.tail.prev
            self._unlink(oldest)
            del self.map[oldest.key]  # why the node stores its key
        node = Node(key, value)
        self._add_front(node)
        self.map[key] = node

JavaScript's Map remembers insertion order, so deleting a key and setting it again marks it as used, and the oldest key is map.keys().next().value. Python's collections.OrderedDict offers move_to_end and popitem(last=False). These shortcuts are fine in real code, but an interviewer asking for an LRU cache usually expects you to build the list yourself.

ApproachTimeSpaceWhy
Min-stackO(1) for every operationO(n)Each operation touches only the tops of two stacks. The second stack doubles the memory used.
LRU cacheO(1) for get and putO(capacity)One map lookup plus a fixed number of pointer changes.

Other combinations of structures

The same method produces several other designs that are asked often. Each one comes from picking the structure for each operation and then deciding how the parts point at each other.

Insert, delete and random element in O(1)

A hash map alone cannot return a random element, and an array alone cannot find or delete a value quickly. Store the values in an array and keep a map from each value to its index in the array. Insert appends to the array and records the index. To delete a value, copy the last array item into the deleted slot, update that item's index in the map, remove the last array item, and delete the value from the map. Picking a random element is a random index into the array. If the value being deleted is itself the last item, the copy and the removal touch the same slot, so make sure the map entry is deleted after the index update and not before it.

Running median with two heaps

A max-heap holds the smaller half of the numbers seen so far and a min-heap holds the larger half. After each insertion the two heaps are rebalanced so that their sizes differ by at most one. The median is the top of the larger heap, or the average of both tops when the sizes are equal. Insertion costs O(log n) and reading the median costs O(1). A sorted array also works, but inserting into it costs O(n). See Heaps and Priority Queues.

Top-k leaderboard with changing scores

A heap alone cannot update the score of an arbitrary entry efficiently. Keep a hash map with the current score of each player, and push a new heap entry whenever a score changes. When you read the top of the heap, discard any entry whose score no longer matches the map, because it is out of date. This is called lazy deletion. It keeps updates at O(log n) and leaves old entries in the heap until they reach the top.

When combining structures is not the answer

If the required operations include anything in sorted order, such as "the smallest key greater than x", a hash map cannot help, because it has no order. The answer is then a balanced tree or a sorted structure, and the time is O(log n) rather than O(1). If the input is small, or the interviewer does not state a time requirement, a plain array scan is also an acceptable first answer; say so, and then improve it.

Pitfalls

In the interview

You can recognise these problems by the statement. It asks you to design a class, lists several methods, and gives a required time for each, usually O(1) on average. Phrases such as "least recently used", "get the minimum", "get a random element" or "the median of a stream" each point to a known combination. Start by writing the operations and their required times, say which structure covers each one, and then explain how the structures refer to each other. Interviewers usually care more about whether you can state the invariant and keep both structures in sync than about the exact code.

Questions to expect:

  • "What would you ask before starting?" Ask what get should return for a missing key, whether put on an existing key counts as a use, whether the capacity can be zero, and whether the keys and values can be of any type. Interviewers expect these questions, and the answers change the code in small ways.
  • "Why a doubly linked list and not a singly linked one?" Removing a node from the middle needs the node before it. With a prev pointer you get it directly, and with a singly linked list you would walk from the head, which makes get O(n).
  • "Why does the node store its key?" When the cache is full you take the oldest node from the end of the list, and you must delete that node's entry from the map. The node is the only place that can tell you which key that is.
  • "Can you reduce the extra space of the min-stack?" Yes. Push onto the second stack only when the new value is less than or equal to the current minimum, and pop from it only when the popped value equals the minimum. The worst case, a strictly decreasing sequence, is still O(n).
  • "What changes for a least frequently used (LFU) cache?" Recency is no longer enough, because you also track how many times each key was used. A common design keeps a map from key to node, a map from each count to a doubly linked list of the keys with that count, and the current minimum count. A use moves a node from its count's list to the next count's list, and eviction removes the oldest node in the list for the minimum count. All operations stay O(1).
  • "How would you make the cache thread-safe?" Even get changes the list, so a read is also a write. The simplest answer is one lock around every method. If contention is a problem, split the cache into several independent shards chosen by hashing the key, each with its own lock and its own list.
Quick check

A min-stack holds values [4, 6, 1, 8] from bottom to top. What does mins contain?

Why does an LRU cache use a doubly linked list?

An LRU cache has capacity 2. The calls are put(a), put(b), get(a), put(c). Which key is evicted?

What to practise next

Build the min-stack in Lowest Point on the Trail, then try Two-Spike Order Rail, which builds a queue from two stacks, and Live Median House Price, which uses two heaps. Monotonic Stack and Queues and Deques cover the parts needed for a queue with a maximum.