coding round · ~20 min
JavaScriptadvanced

Design an LRU cache

Implement a class LRUCache that holds at most capacity entries and evicts the least recently used one when it overflows. Both operations should take O(1) time on average.

  • new LRUCache(capacity) creates an empty cache
  • get(key) returns the stored value and marks the key as recently used, or returns -1 if the key is missing
  • put(key, value) inserts or updates the key and marks it as recently used; if the cache now holds more than capacity entries, remove the least recently used one

Example with const cache = new LRUCache(2):

  • cache.put(1, 1); cache.put(2, 2); cache.get(1) → 1
  • cache.put(3, 3) evicts key 2, because key 1 was used more recently
  • cache.get(2) → -1
  • cache.put(1, 'one') updates key 1 without evicting anything

Define LRUCache in the editor. 8 tests will call it.

solution.js
class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    // Hint: a Map remembers the order in which keys were inserted.
  }

  get(key) {
    // Return the value and mark the key as recently used, or -1 if it's missing.
  }

  put(key, value) {
    // Insert or update the key. Evict the least recently used key when over capacity.
  }
}

Tests⌘/Ctrl + Enter to run

returns -1 for missing keys
stores and retrieves values
evicts the least recently used key when over capacity
get() marks a key as recently used
updating an existing key does not evict anything
updating an existing key marks it as recently used
returns stored falsy values instead of -1
passes a longer sequence of operations
esc