Skip to content
mlmentorship

Join direct key lookup to a doubly linked recency order

Trace promotion and eviction, keep the map and linked order consistent, then observe without refreshing or shrink entry capacity.

Published · 12 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Join direct key lookup to a doubly linked recency order

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative integer capacity, followed by get(key) and put(key, value) calls with integer keys and values. Output. A successful get returns the stored value; a missing key returns -1. A put stores or updates the value without returning one. Rules. A successful read or any write makes that key most recently used; a miss does not change recency. If a new key exceeds capacity, remove the least recently used entry. Capacity counts entries, not bytes or time. Capacity zero retains nothing. Example. With capacity 2, call put(1, 10), put(2, 20), get(1), then put(3, 30). The read returns 10; key 2 is evicted, so get(2) returns -1.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

The map gives direct node access while the doubly linked order exposes the eviction candidate at its left edge.

Problem trace

Reading key 1 moves it ahead of key 2 for the next eviction

Input and goalSupport `get` and `put` in constant time. Remove the least recently used item when the cache is full.
Initialize empty cacheCreate least and most sentinels, link them together, and start with an empty key-to-node map.
least↔most
inputcapacity=2; put(1,10), put(2,20), get(1), put(3,30), get(2)map{}linkseach shown adjacency has both previous and next linkssize0 / 2
input
capacity=2; put(1,10), put(2,20), get(1), put(3,30), get(2)
bidirectional
true
map
{}

Recognize it
The interface requires both O(1) key lookup and O(1) least-recent eviction, which no single ordinary array, map, or queue provides alone.
Keep true
Every map entry points to exactly one node between the sentinels, and list order is least-recent to most-recent; successful access moves that same key to the right edge.
Reuse it
Combine an index with an ordered linked structure whenever a system needs direct identity lookup plus constant-time promotion, removal, or boundary eviction.
Create least and most sentinels, link them together, and start with an empty key-to-node map. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is key 2 evicted after get(1)? Which two structures must stop referencing its node?
Full interview answer 12 min read

Maintain a bounded key-value cache that evicts the least recently used entry when a new entry needs room.

Problem

Input. A nonnegative integer capacity, followed by get(key) and put(key, value) calls with integer keys and values.

Output. A successful get returns the stored value; a missing key returns -1. A put stores or updates the value without returning one.

Rules. A successful read or any write makes that key most recently used; a miss does not change recency. If a new key exceeds capacity, remove the least recently used entry. Capacity counts entries, not bytes or time. Capacity zero retains nothing.

Example. With capacity 2, call put(1, 10), put(2, 20), get(1), then put(3, 30). The read returns 10; key 2 is evicted, so get(2) returns -1.

Picture

The map locates a node directly by key. Between the least and most sentinels, each adjacency has both next and previous links. The leftmost real node is the eviction candidate.

OperationReturned valueKeys from least to most recent
put(1,10)None1
put(2,20)None1,2
get(1)102,1
put(3,30)None1,3; key 2 evicted
get(2)-11,3; unchanged

At public operation boundaries, map entries and interior list nodes correspond one-to-one. Every neighboring pair agrees in both link directions. To unlink a node, join its previous and next neighbors directly in both directions. To refresh it, insert it immediately before most. To evict, remove least.next from the chain and delete its map entry.

The frames include transient detachment and overflow, where public-boundary agreement does not yet hold. The new node briefly raises size to three before eviction restores capacity two.

Problem trace

Reading key 1 moves it ahead of key 2 for the next eviction

Worked example: a read changes the victim of the next evictionWith key 1 older than key 2, reading 1 moves it to most-recent position. Inserting key 3 then evicts key 2.A read changes age, so the nextinsertion changes its victimBefore: one is oldest12oldestnewestget(1): two becomes oldest21oldestnewestInsert three: evict the now-oldesttwo13oldestnewest2out
Read it this way: With key 1 older than key 2, reading 1 moves it to most-recent position. Inserting key 3 then evicts key 2. Without get(1), which key would the insertion of three evict instead?
Reference drawing

Problem trace

Reading key 1 moves it ahead of key 2 for the next eviction

Worked example: a read changes the victim of the next evictionWith key 1 older than key 2, reading 1 moves it to most-recent position. Inserting key 3 then evicts key 2.A read changes age, so the nextinsertion changes its victimBefore: one is oldest12oldestnewestget(1): two becomes oldest21oldestnewestInsert three: evict the now-oldesttwo13oldestnewest2out
Execution trace
Input and goalSupport `get` and `put` in constant time. Remove the least recently used item when the cache is full.
Initialize empty cacheCreate least and most sentinels, link them together, and start with an empty key-to-node map.
least↔most
inputcapacity=2; put(1,10), put(2,20), get(1), put(3,30), get(2)map{}linkseach shown adjacency has both previous and next linkssize0 / 2
input
capacity=2; put(1,10), put(2,20), get(1), put(3,30), get(2)
bidirectional
true
map
{}

Recognize it
The interface requires both O(1) key lookup and O(1) least-recent eviction, which no single ordinary array, map, or queue provides alone.
Keep true
Every map entry points to exactly one node between the sentinels, and list order is least-recent to most-recent; successful access moves that same key to the right edge.
Reuse it
Combine an index with an ordered linked structure whenever a system needs direct identity lookup plus constant-time promotion, removal, or boundary eviction.
Create least and most sentinels, link them together, and start with an empty key-to-node map. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is key 2 evicted after get(1)? Which two structures must stop referencing its node?
Read it this way: With key 1 older than key 2, reading 1 moves it to most-recent position. Inserting key 3 then evicts key 2. Without get(1), which key would the insertion of three evict instead?

Code

from __future__ import annotations
from dataclasses import dataclass

@dataclass(eq=False, slots=True)
class _CacheNode:
   key: int = 0
   value: int = 0
   previous: _CacheNode | None = None
   next: _CacheNode | None = None


class LRUCache:
   def __init__(self, capacity: int) -> None:
      self.capacity = capacity
      self.nodes: dict[int, _CacheNode] = {}
      self.least = _CacheNode()
      self.most = _CacheNode()
      self.least.next = self.most
      self.most.previous = self.least

   def _remove(self, node: _CacheNode) -> None:
      node.previous.next = node.next
      node.next.previous = node.previous

   def _append(self, node: _CacheNode) -> None:
      node.previous = self.most.previous
      node.next = self.most
      self.most.previous.next = node
      self.most.previous = node

   def get(self, key: int) -> int:
      if key not in self.nodes:
         return -1
      node = self.nodes[key]
      self._remove(node)
      self._append(node)
      return node.value

   def put(self, key: int, value: int) -> None:
      if key in self.nodes:
         self._remove(self.nodes[key])

      node = _CacheNode(key, value)
      self.nodes[key] = node
      self._append(node)

      if len(self.nodes) > self.capacity:
         removed = self.least.next
         self._remove(removed)
         del self.nodes[removed.key]

Pointer rewires take constant work; key lookup is expected under ordinary hashing assumptions, not a worst-case guarantee. Steady storage is for capacity , including two sentinels. Zero capacity immediately evicts every inserted entry.

An existing-key put allocates a replacement node here; a successful get moves the same node. Misses return -1, which is indistinguishable from a stored -1 by return value alone.

Failure Check

Unlinking without map deletion leaves an evicted key readable. Updating only one link direction breaks later removals. A plain list also needs a linear scan to locate an arbitrary accessed key.

Change to Nonpromoting Observation

New task: Read a value without protecting its key from eviction.

Picture and change: Look up the value without unlinking or appending. This driver accepts put, get and peek records and returns reads plus final key order.

def cache_peek_trace(capacity, operations):
   cache, reads = LRUCache(capacity), []
   for operation in operations:
      name, *arguments = operation
      if name == "put":
         cache.put(*arguments)
      elif name == "get":
         reads.append(cache.get(*arguments))
      else:
         node = cache.nodes.get(arguments[0])
         reads.append(node.value if node is not None else -1)
   order, node = [], cache.least.next
   while node is not cache.most:
      order.append(node.key)
      node = node.next
   return [reads, order]

Check: Put keys 1,2, peek 1, then put 3: order becomes [2,3] and a subsequent get(1) misses. Replacing that peek with get would instead evict key 2.

Use when: Monitoring must not change replacement decisions.

Change Entry Capacity

New task: Resize an existing cache to a nonnegative capacity.

Picture and change: Update capacity and repeatedly evict the least-recent node until size fits.

def resized_cache_keys(capacity, entries, new_capacity):
   if new_capacity < 0:
      raise ValueError("negative capacity")
   cache = LRUCache(capacity)
   for key, value in entries:
      cache.put(key, value)
   cache.capacity = new_capacity
   while len(cache.nodes) > new_capacity:
      removed = cache.least.next
      cache._remove(removed)
      del cache.nodes[removed.key]
   keys, node = [], cache.least.next
   while node is not cache.most:
      keys.append(node.key)
      node = node.next
   return keys

Check: Entries [(1,10),(2,20),(3,30)], capacity 3, then new capacity 1 leave [3]. Shrinking to zero removes all entries. The resize loop costs one eviction per removed entry, not constant time. This complete helper also constructs the cache and lists its remaining keys.

Use when: The allowed entry count changes during operation.

Transfer Check

Does recency ordering also solve expiry or byte-weighted capacity?

Answer

No. Expiry needs time-validity rules, and weighted capacity needs per-entry weights with possibly several evictions per insertion.