Design an O(1) eviction cache
Company: Palo Alto Networks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates data structure and algorithmic design skills within the Coding & Algorithms domain, focusing on cache eviction policies and techniques for achieving average O(1) get/put operations. It is commonly asked to test reasoning about time and space complexity, handling of capacity and edge cases, and demonstrates a blend of conceptual understanding and practical application.
Constraints
- 0 <= capacity <= 100000
- 0 <= len(ops) <= 200000
- Each op is either ["put", key, value] or ["get", key]
- Keys and values are 32-bit signed integers (e.g., -1e9 <= key,value <= 1e9)
- Average O(1) time for get and put
- Updates to existing keys must refresh recency
Hints
- Use a hash map from key to a node in a doubly linked list to achieve O(1) access and updates.
- Maintain a doubly linked list ordered by recency: most recent at the head, least recent at the tail.
- On get: if found, move the node to the head before returning its value.
- On put: if key exists, update value and move to head; else insert a new node at head. If size exceeds capacity, remove the tail node and delete it from the map.
- Sentinel head/tail nodes simplify insert/remove operations. Handle capacity=0 as a special case.