Skip to the solution
HardLow-Level DesignAsked in 20246 min read

Implement an LFU (Least Frequently Used) Cache

636 views

The problem

Problem, as an interviewer would state it: "Implement an LFU (Least Frequently Used) cache with get(key)/put(key, value), both in O(1) — evicting the LEAST FREQUENTLY accessed key when full, with ties broken by LEAST RECENTLY used among equally-frequent keys."

Examples:

Code
cache.put(1, "A"); cache.put(2, "B");
cache.get(1);       // freq(1)=2, freq(2)=1
cache.put(3, "C");  // evicts key 2 (lowest freq)

Clarifying questions expected:

  • When two keys have the SAME access frequency, which one is evicted — is a tie-break rule needed?
  • Does calling get on a key increment its frequency, and does put on an ALREADY-existing key do the same?
  • Must both get and put genuinely run in O(1), not just amortized or "close to" O(1)?

Code / implementation expected: Yes — real, direct proof of correct frequency-based eviction, PLUS a real, direct proof of the LRU tie-break among two keys sharing the identical frequency.

  • js-coding
  • utility
  • algorithm

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: the LFU cache correctly evicts by frequency, AND separately, correctly applies the LRU tie-break between two equally-frequent keys

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 148 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 nextHard

Implement a Cancelable Promise (with CancelToken / AbortController)

Continue