Design O(1) random-sampling set
Company: xAI
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's competency in data-structure design, randomized algorithms, and algorithmic complexity analysis within the Coding & Algorithms domain, with a focus on achieving expected O(1) operations for insert, remove, and uniform sampling.
Constraints
- 0 <= len(commands) == len(values) <= 200000
- commands[i] is one of "insert", "remove", or "get_random"
- -1000000000 <= values[i] <= 1000000000 for insert/remove operations
- For every get_random operation, the set is non-empty and 0 <= values[i] < current set size
- Duplicate values are not stored; inserting an existing value must not change the set
Examples
Input: (["insert", "insert", "get_random", "remove", "get_random", "insert", "remove"], [1, 2, 0, 1, 0, 2, 3])
Expected Output: [1, 1, 1, 1, 2, 0, 0]
Explanation: Insert 1 and 2. Random index 0 returns 1. Removing 1 swaps 2 into the only slot, so the next random index 0 returns 2. Inserting duplicate 2 fails, and removing absent 3 fails.
Input: ([], [])
Expected Output: []
Explanation: No operations produce no results.
Hints
- A dynamic array gives O(1) access by random index, but cannot remove arbitrary elements in O(1) unless you avoid preserving order.
- Keep a hash map from value to its index in the array. To remove a value, move the last array element into the removed value's slot, update that moved element's index, then pop the last position.