Build a Least-Recently-Used Store
Company: XPeng
Role: Data Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: 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.
Read the full XPeng Data Engineer interview experience this question came from
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.
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.