As reported: Okta Staff Engineer (Java full stack, 10+ YOE), round 1 coding (2026): LeetCode 381 — the optimal approach and its complexity, with follow-ups on handling duplicates efficiently and on edge cases.
Implement RandomizedCollection, a multiset that supports, each in average O(1) time. This is LeetCode 381 — Insert Delete GetRandom O(1) - Duplicates allowed:
insert(val)— add one copy ofval; returntrueifvalwas not present before, elsefalse.remove(val)— remove one copy ofvalif present; returntrueif something was removed.getRandom()— return a random element; each copy is equally likely, so a value's probability is proportional to how many copies it has.
Example
["RandomizedCollection","insert","insert","insert","getRandom","remove","getRandom"]
[[],[1],[1],[2],[],[1],[]]
-> [null,true,false,true,(1 with prob. 2/3, 2 with prob. 1/3),true,(1 or 2, each 1/2)]
Constraints: -2^31 ≤ val ≤ 2^31 − 1; at most 2 · 10^5 calls; getRandom is only called when the collection is non-empty.
Code runner format: two lines, LeetCode's format: the list of operations (starting with "RandomizedCollection"), then the list of their argument lists. Implement the class RandomizedCollection with insert, remove and getRandom; the harness prints the list of return values (null for methods that return nothing). The harness checks the return values and the distribution of getRandom and prints "ok".