Classic question but I still fumbled the implementation a bit.
Use a hash map for O(1) access to cache items 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. For get, move the accessed node to the head; for 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 (not singly) to achieve O(1) removal from the middle, and consider thread-safety if the cache might be accessed concurrently.
Confirm the cache capacity, whether keys and values are integers, and if thread-safety is required. Also, clarify the expected behavior when updating an existing key.
Select a hash map for O(1) key lookup and a doubly linked list to track usage order. Explain that the hash map stores key to node references, and the list maintains MRU to LRU order.
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 new node, add to head, and if capacity exceeded, remove tail and delete from map.
Consider capacity 0 or 1, updating an existing key, and eviction when the cache is full. Ensure that the linked list and hash map stay in sync.
State that both get and put run in O(1) time because hash map operations are O(1) and linked list insertions/removals are O(1) given direct node references.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.