← Bytedance Interview Insights
Classic question but I still fumbled the eviction logic for a second.
Start by clarifying the requirements: fixed capacity, O(1) get and put operations. Then explain that a hash map combined with a doubly linked list achieves this, with the map providing O(1) access to nodes and the list maintaining recency order. Walk through the implementation details, including edge cases like updating existing keys and evicting the least recently used item when capacity is exceeded.
Pro tip: Mention that you can use a dummy head and tail node to simplify edge cases in the doubly linked list, and discuss how this design is used in real systems like Redis or CPU caches. This shows practical awareness beyond textbook knowledge.
Confirm that the cache has a fixed capacity, supports get and put in O(1) time, and evicts the least recently used item when full. Ask about thread safety if relevant.
Explain that a hash map (for O(1) key lookup) and a doubly linked list (for O(1) insertion, deletion, and recency ordering) together meet the requirements.
Define a node with key, value, prev, and next pointers. Describe helper methods to add a node to the front (most recently used) and remove a node from anywhere in the list.
For get: if key exists, move node to front and return value; else return -1. For put: if key exists, update value and move to front; else create new node, add to front, and if capacity exceeded, remove the tail node and delete its key from the map.
State that both operations are O(1) time and O(capacity) space. Discuss edge cases like capacity 0 or 1, updating existing keys, and handling null values.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.