Design a Randomized Multiset
LinkedInSoftware Engineer · Technical ScreenLast updated
This question evaluates the ability to design and implement a randomized multiset that correctly handles duplicate integer occurrences while providing expected O(1) insert, remove, and uniform getRandom operations, testing knowledge of data structures, randomness, and performance constraints.
Implement a data structure for integers that allows duplicate values and supports the following operations in expected O(1) time:
insert(val): Add one occurrence ofval. Returntrueifvalwas not already present in the collection, otherwise returnfalse.remove(val): Remove one occurrence ofvalif it exists. Returntrueif an element was removed, otherwise returnfalse.getRandom(): Return one stored element chosen uniformly at random from all stored occurrences.
Your design must handle duplicates correctly. Be prepared to explain important edge cases during deletion, especially when the element being removed is already the last element in the array, or when the value moved into the deleted slot is the same as the value being removed.
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.