Set of Active Sessions with Constant-Time Random Selection
Last updated: November 29, 2026
Quick Overview
Design a set of session ids supporting insert(id), remove(id), and get_random() which returns a uniformly random present id, each in average O(1) time.
0
0
0 solved
Design a set of session ids supporting insert(id), remove(id), and get_random() which returns a uniformly random present id, each in average O(1) time.
A Google design-a-data-structure question, framed around sampling live sessions for quality audits. The interviewer checks that you combine an array (for random indexing) with a hash map (for lookup) and remove in O(1) by swapping with the last element.
What the Interviewer Expects
- Notes that a hash set alone cannot sample uniformly in O(1)
- Stores values in an array and their indices in a map
- Removes by swapping the target with the last element, then popping
- Updates the moved element's index in the map
- Handles removing the last element itself
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Allow duplicates, with get_random weighted by multiplicity.
- Add get_random_excluding(id) without rejection loops.
- Make it thread safe under heavy concurrent use.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
insert(x): add if absent, return whether it was added.remove(x): delete if present, return whether it was removed.get_random(): uniform over current elements; called only when non-empty....
High-Level Design
Keep items, a dense list of the current values, and pos, a map from value to its index in items. Insert appends and records the index. Remove looks up index i, moves the last element into slot i...