Implement Cache Eviction And Seat Assignment
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of data structure design and algorithmic reasoning, covering cache eviction policies (least-recently-used) and seat-assignment strategies that maximize minimum distance.
Part 1: Simulate an LRU Cache
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- Each operation is either ('put', key, value) or ('get', key)
- -10^9 <= key, value <= 10^9
Examples
Input: (2, [('put', 1, 1), ('put', 2, 2), ('get', 1), ('put', 3, 3), ('get', 2), ('put', 4, 4), ('get', 1), ('get', 3), ('get', 4)])
Expected Output: [1, -1, -1, 3, 4]
Explanation: After accessing key 1, key 2 becomes least recently used and is evicted when key 3 is inserted. Later key 1 is evicted when key 4 is inserted.
Input: (2, [('put', 1, 1), ('put', 2, 2), ('put', 1, 10), ('put', 3, 3), ('get', 1), ('get', 2), ('get', 3)])
Expected Output: [10, -1, 3]
Explanation: Updating key 1 also refreshes its recency, so key 2 is evicted when key 3 is inserted.
Input: (1, [('get', 5), ('put', 5, 50), ('get', 5), ('put', 6, 60), ('get', 5), ('get', 6)])
Expected Output: [-1, 50, -1, 60]
Explanation: With capacity 1, every new key replaces the previous one.
Input: (3, [])
Expected Output: []
Explanation: No operations means no 'get' results.
Hints
- Use a hash map so you can find a key's node in O(1) time.
- You also need a structure that can remove and reinsert nodes in O(1) when their recency changes.
Part 2: Assign Seats to Maximize Distance
Constraints
- 1 <= n <= 2 * 10^5
- 0 <= k <= n
- Seats are never freed
- If multiple optimal seats exist, choose the smallest index
Examples
Input: (10, 4)
Expected Output: [0, 9, 4, 2]
Explanation: The first seats chosen are 0, then 9, then 4. After that, seats 2 and 6 are tied, so choose the smaller index 2.
Input: (1, 1)
Expected Output: [0]
Explanation: Only one seat exists.
Input: (5, 5)
Expected Output: [0, 4, 2, 1, 3]
Explanation: The row eventually fills while always taking the seat with maximum nearest-neighbor distance.
Input: (7, 0)
Expected Output: []
Explanation: No assignments requested.
Hints
- Think of the empty seats as intervals between already occupied seats.
- A priority queue can help you always pick the interval whose best seat gives the largest distance; break ties using the seat index.