← Bytedance Interview Insights
Use a hash map for O(1) key lookup and a doubly linked list to track usage order, with the most recently used at the head and least recently used at the tail. For get, move the accessed node to the head; for put, insert or update and move to head, evicting the tail if capacity is exceeded. This combination ensures both operations run in O(1) average time.
Pro tip: Mention that you would use dummy head and tail nodes to simplify edge cases in the linked list, and discuss thread-safety considerations if the cache might be accessed concurrently.
Confirm the capacity is fixed and positive, and that get and put must be O(1) average time. Ask about thread-safety requirements and whether keys/values are integers or generic types.
Select a hash map for O(1) key-to-node lookup and a doubly linked list to maintain usage order. Explain that the hash map stores references to nodes in the list, enabling O(1) updates.
Describe a node with key, value, prev, and next pointers. Outline helper methods to add a node to the head (most recently used) and remove a node from the list, using dummy head and tail sentinels to avoid null checks.
For get: if key exists, move its node to the head and return value; else return -1. For put: if key exists, update value and move to head; else create a new node, add to head, and if size exceeds capacity, remove the tail node and delete its key from the map.
State that both operations are O(1) average time due to hash map and linked list operations. Discuss edge cases: capacity 0 or 1, updating existing key, and eviction when full.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.