← Bytedance Interview Insights
It's labeled Hard but anyone who's done a few rounds of prep has seen this one.
Use a hash map for O(1) access to cache entries and a doubly linked list to maintain the order of usage, with the most recently used at the head and least recently used at the tail. On get, move the accessed node to the head; on put, add new nodes to the head and evict the tail when capacity is exceeded.
Pro tip: Mention that you would use a doubly linked list instead of a singly linked list to achieve O(1) removal of a node given its reference, and discuss how to handle edge cases like updating an existing key or capacity of zero.
Confirm that both get and put must be O(1), and discuss assumptions like positive capacity, thread-safety, and whether keys/values are integers or generic.
Select a hash map for O(1) key lookup and a doubly linked list for O(1) insertion, deletion, and reordering of nodes.
Define a node with key, value, prev, and next pointers. The cache maintains a map from key to node, a head and tail sentinel, and a capacity.
For get: if key exists, move node to head and return value; else return -1. For put: if key exists, update value and move to head; else create new node, add to head, and if size exceeds capacity, remove tail node and its key from map.
Explain that both operations are O(1) time and O(capacity) space. Discuss edge cases: capacity 0, 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.