Skip to the solution
MediumDSA6 min read

Implement LRU Cache (get/put with O(1))

338 views

The problem

Problem, as an interviewer would state it: "Design an LRU cache with get(key) and put(key, value) in O(1). Evict the least recently used entry when capacity is exceeded. Use a Map or a doubly linked list."

Examples:

Code
const c = new LRUCache(2);
c.put(1, 1); c.put(2, 2);
c.get(1);    // 1
c.put(3, 3); // evicts key 2
c.get(2);    // not found

Clarifying questions expected:

  • Does a get count as a "use" that refreshes recency, and does put on an existing key too?
  • What should get return for a missing key?
  • What if capacity is zero or invalid?

Code / implementation expected: Yes — real, direct proof of the eviction order, recency refresh on both operations, and the O(1) scaling.

  • lru
  • cache
  • map
  • doubly-linked-list

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: an LRU cache on Map insertion order reproduces the LeetCode trace, refreshes recency on update, and evicts the oldest entry

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 119 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Promise Retry with Backoff

Continue