☰ All problems

34. LRU Cache

Design a fixed-size key-value cache that evicts the least recently used entry when it runs out of room.

Implement the LRUCache class:

  • LRUCache(capacity) creates an empty cache that can hold at most capacity entries.
  • get(key) returns the value stored for key, or -1 if the key is not in the cache.
  • put(key, value) stores value under key, replacing any existing value. If this adds a new key and the cache now holds more than capacity entries, remove the entry that was used least recently.

Both a successful get and any put count as a use of that key. A get for a missing key changes nothing. Both operations must run in O(1) average time.

Example 1
Input: ["LRUCache","put","put","get","put","get","get","put","put","get","get","get"]
[[2],[1,10],[2,20],[1],[3,30],[2],[3],[1,15],[4,40],[3],[1],[4]]
Output: [null,null,null,10,null,-1,30,null,null,-1,15,40]

Explanation: Reading key 1 makes key 2 the least recently used, so adding key 3 evicts key 2. Later, updating key 1 leaves key 3 as the oldest, and adding key 4 evicts it.

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • At most 2 * 10^5 calls to get and put
💡 Hint 1

A hash map gives O(1) lookup, but it does not remember which key was used least recently. What structure can reorder items in O(1)?

💡 Hint 2

Keep the entries in a doubly linked list ordered by recency, and let the map point at the list nodes so you can unlink any entry instantly.

💡 Hint 3

Sentinel head and tail nodes remove the empty-list edge cases. In JavaScript, a Map already iterates in insertion order, which you can exploit.

class LRUCache {
  /** @param {number} capacity */
  constructor(capacity) {

  }

  /**
   * @param {number} key
   * @return {number}
   */
  get(key) {

  }

  /**
   * @param {number} key
   * @param {number} value
   * @return {void}
   */
  put(key, value) {

  }
}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc