Build a Least-Recently-Used Store
Company: XPeng
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of caching and eviction policies and practical proficiency with data structures such as hash tables and ordered collections for tracking and updating recency.
Constraints
- 1 <= capacity <= 1000
- 0 <= len(operations) <= 2000
- len(operations) == len(keys) == len(values)
- `operations[i]` is either "get" or "put"
- -10^9 <= keys[i], values[i] <= 10^9
Examples
Input: (2, ["put", "put", "get", "put", "get", "get", "put", "get"], [1, 2, 1, 3, 2, 3, 1, 1], [10, 20, 0, 30, 0, 0, 15, 0])
Expected Output: [10, -1, 30, 15]
Explanation: After `get(1)`, key 1 becomes most recent, so inserting key 3 evicts key 2. Later, updating key 1 changes its value to 15 and keeps it most recent.
Input: (1, ["put", "put", "get", "put", "get", "get"], [1, 2, 1, 2, 1, 2], [5, 6, 0, 7, 0, 0])
Expected Output: [-1, -1, 7]
Explanation: With capacity 1, inserting key 2 evicts key 1. Updating key 2 does not evict anything. The two `get` calls for key 1 return -1, and `get(2)` returns 7.
Input: (2, ["put", "put", "get", "put", "get", "get"], [-1, 5, -1, 6, 5, 6], [-10, 50, 0, 60, 0, 0])
Expected Output: [-10, -1, 60]
Explanation: Negative keys and values are allowed. Accessing key -1 makes it most recent, so inserting key 6 evicts key 5.
Input: (2, ["put", "put", "put", "put", "get", "get", "get"], [1, 2, 1, 3, 1, 2, 3], [1, 2, 3, 4, 0, 0, 0])
Expected Output: [3, -1, 4]
Explanation: Updating key 1 makes it most recent, so when key 3 is inserted, key 2 is evicted. The later gets confirm that key 1 remains with value 3, key 2 is gone, and key 3 exists.
Input: (3, [], [], [])
Expected Output: []
Explanation: No operations means there are no `get` results to return.
Hints
- Use a hash map to store the current value for each key.
- Keep a list of keys ordered from least recently used to most recently used. Whenever a key is accessed or updated, move it to the end.