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:
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
geton a key increment its frequency, and doesputon an ALREADY-existing key do the same? - Must both
getandputgenuinely 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.