← Salesforce Interview Insights
I knew LRU cold but LFU is a different beast.
Use a combination of a hash map and a doubly linked list of frequency nodes, where each frequency node contains a doubly linked list of keys with that frequency. This allows O(1) access, update, and eviction by maintaining pointers to the least frequently used node and the least recently used key within it.
Pro tip: Emphasize that the design must handle both frequency updates and recency ordering within the same frequency, and discuss how to maintain O(1) by using sentinel nodes and careful pointer manipulation.
Confirm that both get and put must be O(1) average time, and that eviction removes the least frequently used key, breaking ties by least recently used. Ask about cache capacity and whether keys/values are integers or generic.
Propose a hash map from key to a node containing value and frequency, and a doubly linked list of frequency nodes. Each frequency node has a doubly linked list of keys with that frequency, ordered by recency (most recent at head).
If key exists, retrieve its node, increment its frequency, and move it to the appropriate frequency list. If the frequency node doesn't exist, create it and insert it in the correct position relative to the current frequency node.
If key exists, update value and increment frequency (similar to get). If key is new, check capacity; if full, evict the least frequently used key (tail of the lowest frequency list). Then insert the new key with frequency 1.
Discuss handling capacity 0, updating frequency nodes when lists become empty, and using sentinel nodes to simplify pointer operations. Mention that all operations remain O(1) due to constant number of pointer updates.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.