Design set with O(1) random access
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates skill in designing a composite data structure that supports average O(1) insertion, deletion, and uniform random access, and tests understanding of hashing, indexing, randomness, and concurrency control.
Constraints
- 1 <= len(operations) <= 2 * 10^5
- len(values) == len(operations)
- Each operation is one of 'add', 'delete', or 'getRandom'
- For 'add' and 'delete', values[i] contains exactly one integer; for 'getRandom', values[i] is []
- -10^9 <= x <= 10^9
- All operations should run in O(1) average time
Examples
Input: (['add','add','getRandom','delete','getRandom','add','getRandom'], [[1],[2],[],[1],[],[2],[]], 7)
Expected Output: [True, True, 1, True, 2, False, 2]
Explanation: After inserting 1 and 2, the first deterministic random choice picks index 0, so it returns 1. Deleting 1 leaves only 2. Adding 2 again fails because it is already present.
Input: (['getRandom','add','add','delete','delete','getRandom'], [[],[5],[5],[7],[5],[]], 1)
Expected Output: [None, True, False, False, True, None]
Explanation: Calling getRandom on an empty set returns None. Adding 5 twice inserts it only once. Deleting 7 fails because it is not present. After deleting 5, the set becomes empty again.
Input: (['add','add','add','delete','delete','getRandom'], [[-1],[10],[4],[10],[4],[]], 99)
Expected Output: [True, True, True, True, True, -1]
Explanation: Deleting 10 swaps 4 into its slot. Deleting 4 after that checks whether the moved index was updated correctly. Only -1 remains, so getRandom returns -1.
Input: (['getRandom','add','add','getRandom','delete','getRandom'], [[],[8],[9],[],[8],[]], 1)
Expected Output: [None, True, True, 8, True, 9]
Explanation: The first getRandom is on an empty set, so it returns None and does not advance the random state. The next getRandom on [8, 9] therefore uses the initial seed and picks 8. After deleting 8, only 9 remains.
Input: (['add','add','add','getRandom','delete','getRandom'], [[4],[5],[6],[],[5],[]], 2)
Expected Output: [True, True, True, 6, True, 4]
Explanation: With seed 2, the first random index for [4, 5, 6] is 2, so it returns 6. Deleting 5 swaps 6 into index 1, leaving [4, 6]. The next deterministic random choice picks index 0, so it returns 4.
Hints
- You need both fast membership/index lookup and fast access by numeric position. What two data structures combine to give that?
- Deleting from the middle of an array is expensive unless you replace the removed element with the last element and update that last element's stored index.