← Microsoft Interview Insights
The O(1) part is where most people stumble.
Start by clarifying the O(1) requirement and tie-breaking rule, then propose a design combining a hash map for key-to-node lookup with a frequency-indexed doubly linked list to track usage order. Explain how get and put update frequencies and evict the least frequent, least recently used key in constant time.
Pro tip: Mention that you can implement the frequency lists using a single doubly linked list of nodes where each node represents a frequency bucket, and each bucket contains a doubly linked list of keys—this avoids the need for a separate min-frequency variable and simplifies eviction.
Confirm that both get and put must be O(1) average time, and that eviction removes the least frequently used key, with ties broken by least recently used. Ask about cache size limits and concurrency if relevant.
Propose a hash map from key to node for O(1) access. Each node stores key, value, and frequency. Maintain a doubly linked list of frequency buckets, each containing a doubly linked list of nodes with that frequency, ordered by recency.
On get, look up the node in the hash map. If found, increment its frequency, move it to the appropriate frequency bucket (creating a new bucket if needed), and return its value. If not found, return -1.
On put, if key exists, update its value and increment frequency (similar to get). If new, insert with frequency 1. If capacity is exceeded, evict the least frequent, least recently used node from the lowest frequency bucket.
Explain that all operations are O(1) average due to hash map and constant-time list manipulations. Discuss edge cases like capacity 0, updating existing keys, and tie-breaking.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.