☰ All problems

LRU Cache

A photo app keeps recently viewed thumbnails in a small in-memory cache so that scrolling back is instant. When the cache is full and another thumbnail has to be stored, the app throws out the entry that has gone unused for the longest time.

Implement the LRUCache class:

  • LRUCache(capacity) creates an empty cache that holds at most capacity entries.
  • get(key) returns the value stored under key, or -1 if that key is not cached.
  • put(key, value) stores value under key, overwriting any earlier value. If this adds a new key and the cache now holds more than capacity entries, evict the least recently used entry.

A key counts as used whenever put writes it or get finds it; a get for a missing key changes nothing. Both operations must take O(1) time on average.

Example 1
Input: ["LRUCache","put","put","get","put","get","get","get"]
[[2],[7,70],[3,30],[7],[9,90],[3],[9],[7]]
Output: [null,null,null,70,null,-1,90,70]

Explanation: Reading key 7 makes key 3 the least recently used entry, so storing key 9 evicts key 3.

Example 2
Input: ["LRUCache","put","put","put","put","get","put","get","get","get"]
[[3],[1,100],[2,200],[3,300],[1,111],[2],[4,400],[1],[3],[4]]
Output: [null,null,null,null,null,200,null,111,-1,400]

Explanation: Overwriting key 1 and then reading key 2 leave key 3 as the least recently used, so adding key 4 evicts it. Key 1 keeps its new value 111.

Constraints

  • capacity is between 1 and 3000.
  • Keys are integers from 0 to 10^4, and values are integers from 0 to 10^5.
  • A test makes at most 200,000 calls to get and put combined.
💡 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