LRU implementation using stacks
Filed under Amazon
Free read 3 of 3A pure stack-only implementation is theoretically impossible for O(1) access. Clarify if 'stack' implies a deque or if auxiliary hash maps are allowed.
The question
Implement an LRU cache using only stack data structures. The cache must support get(key) and put(key, value) operations with O(1) average time complexity.
Constraints
- Use only stack data structures
- O(1) average time complexity
- Fixed capacity
Approach
A pure stack-only implementation is theoretically impossible for O(1) access. Clarify if 'stack' implies a deque or if auxiliary hash maps are allowed.
If restricted to stacks, use two stacks to simulate a queue or use a custom linked-stack structure.
Implement put by pushing to stack and get by moving elements to the top of the stack.
Tips
- What they are testing: Verify behavior when the cache is full and when accessing existing vs new keys.
- Common mistake: Assuming stacks allow O(1) middle element removal, which they do not; this requires careful stack management.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.