This question evaluates a candidate's ability to design and implement efficient data structures for caching, including understanding frequency-based eviction policies, maintaining recency ordering for tie-breaking, and meeting strict time-complexity guarantees.
Design and implement an LFU (Least Frequently Used) cache.
The cache supports:
get(key)
: return the value for
key
if present, else return
-1
.
put(key, value)
: insert or update the key with
value
.
Rules:
get
increments that key’s frequency.
put
on an existing key updates the value and increments frequency.
0
, all operations should be no-ops and
get
always returns
-1
.
get
and
put
should run in
amortized O(1)
time.
You may be given a sequence of operations and must output results of get operations.