EvalFrame Technical Mock Interviews & Coding Practice

LRU Cache

Medium · Linked List / Design · Algorithm problem · all problems

Design a data structure that follows the constraints of a **Least Recently Used (LRU) cache**. Implement the `LRUCache` class: * `get(key: number): number` Return the value of the `key` if the key exists, otherwise return `-1`. * `put(key: number, value: number): void` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, evict the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Examples:** ```typescript const lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(1) get and put
  • Space complexity: O(capacity)

JavaScript Map maintains insertion order, allowing O(1) eviction of first key and re-insertion.

Follow-Up Questions Interviewers Ask About LRU Cache

  • How is LRU cache implemented in lower-level languages like C++ or Java?
    Combine a Doubly Linked List (for O(1) node removal and insertion at head) with a Hash Map mapping keys to Node pointers.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.