Skip to question
asic.fyi
DesignVerificationSystemVerilogFirmwareArchitectureInterviews
asic.fyi/Interview questions/Implement an O(1) LRU cache

Hardware interview practice

Implement an O(1) LRU cache

HardData StructuresPYTHON

Implement a fixed-capacity least-recently-used cache with average O(1) get and put. A successful get and every put make the key most recently used.

Try it in the question bankReason first. Then compare.

Keep this exact question selected while you check your answer and review the full solution.

Practice this question →
Reviewed example

Work through one case

Input
capacity=2; put(1,A), put(2,B), get(1), put(3,C)
Expected output
get(1)=A; key 2 is evicted; LRU-to-MRU order is [1, 3]

The successful lookup promotes key 1, making key 2 the single eviction victim when key 3 arrives.

What to cover

Requirements

  1. Reject nonpositive capacity and return -1 for a missing key.
  2. Use a hash map from key to node and a doubly linked list ordered from most to least recently used.
  3. Updating an existing key must update its value and recency without changing cache size.
  4. Inserting past capacity must evict exactly the least-recently-used key from both structures.
Continue practicing

Related questions

Data StructuresBuild an insertion-ordered O(1) set→
asic.fyi · Learn silicon end to end.info@asic.fyi