I knew the vanilla LRU implementation cold, OrderedDict plus a size cap, but the TTL layer threw me off more than I expected.
Start by clarifying requirements and constraints, then propose a design combining a hash map for O(1) access and a doubly linked list for LRU ordering, with each node storing an expiration timestamp. Explain how get checks TTL and removes expired entries, and how put evicts expired entries first, then LRU if needed, before implementing the core operations.
Pro tip: Mention that you would use a min-heap or time-ordered structure to efficiently find expired entries, but since eviction only happens on put, a lazy approach of checking the LRU list for expired entries is often sufficient and simpler. Also, discuss trade-offs between eager vs lazy expiration and how it affects performance and memory.
Ask about expected cache size, TTL granularity, concurrency needs, and whether expired entries should be actively purged or lazily removed. Confirm that get should return -1 and remove expired entries, and put should evict expired first, then LRU.
Propose a hash map (for O(1) key lookup) and a doubly linked list (for O(1) LRU updates). Each node stores key, value, expiration timestamp, and pointers. Optionally, mention a min-heap for expiration tracking if eager cleanup is needed.
For get: check if key exists and not expired; if expired, remove and return -1; else move node to front (most recently used) and return value. For put: if key exists, update value and TTL, move to front; else if at capacity, evict expired entries first (scan from LRU end), then evict LRU if needed; insert new node at front.
Explain that on put, you can scan from the least-recently-used end to find expired entries, removing them until capacity is available or no expired entries remain. If still at capacity, remove the LRU entry. Discuss trade-offs: scanning may be O(n) in worst case, but often fast if few expired entries.
State that get and put are O(1) average for hash map and linked list operations, but eviction may be O(k) where k is number of expired entries scanned. Mention alternative designs like using a min-heap for expiration to achieve O(log n) eviction, and discuss concurrency considerations if needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.