Design O(1) random-sampling set
xAIMachine Learning Engineer · Technical ScreenLast updated
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.
Design a data structure that supports insert(x), remove(x), and get_random() that returns a uniformly random element among the present items, all in expected O(
- time. Detail the algorithms and data structures you would use, how you handle deleting the last element and gaps, and how you would test the uniformity of get_random(). Discuss extensions such as supporting duplicates or thread-safety and the impact on complexity.
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.