Design set with O(1) random access
GoogleSoftware Engineer · Technical ScreenLast updated
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.
Design a data structure ("FancySet") that stores unique integers and supports the following operations, each in average O(1) time:
add(x): Insert valuexif it is not already present. Return whether the insert happened.delete(x): Remove valuexif it exists. Return whether a deletion happened.getRandom(): Return a uniformly random element currently in the set.
Requirements / follow-ups:
- All operations should be average O(1).
- Handle corner cases such as calling
getRandom()on an empty set (define and justify behavior). - Discuss how you would make this data structure thread-safe. Compare using a single lock for the whole set vs finer-grained locking (e.g., element-level locks), and explain trade-offs.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.