LRU Cache – Solution & Complexity
Watch: LRU Cache with a hash map and a doubly linked list
A hash map finds any key's node in O(1); a doubly linked list keeps nodes in order of use, most recent at the front. Every get or put moves the node to the front, and when over capacity the node before the dummy tail is evicted, along with its key, which is why nodes store their key.
Solution Walkthrough
Step 1: Recognize the Pattern
The key pattern is: Hash lookup plus recency ordering supports O(1) operations. Identify the state and invariant before coding.
Step 2: Build the Algorithm
Advance one state transition at a time. Mark or update state before exploring dependent work.
Step 3: Check Edge Cases
Test empty or minimal input, skewed shapes, duplicates where allowed, and impossible outcomes.
Step 4: Solution and Complexity
Time: O(q). Space: O(capacity).