#380

Insert Delete GetRandom O(1)

Medium ArrayList + HashMap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a set that supports insert, remove and getRandom (each element equally likely), all in average O(1) time.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: a set where add, remove and "pick a random element" are all O(1).

Why this works: a list gives random access by index; a map gives value → index lookups. Remove becomes O(1) by moving the last element into the hole instead of shifting everything.

Example: insert 1, insert 2, insert 3, remove 1

list = [1, 2, 3], pos = {1:0, 2:1, 3:2}remove 1: last = 3 moves to index 0list = [3, 2], pos = {3:0, 2:1}getRandom picks index 0 or 1 → 3 or 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to update the moved element's index in the map, or removing the map entry before the swap when the removed value is itself the last element.