0 XP · 0 scenes

Insert Delete GetRandom O(1)

MediumArray + dictionary, delete by swapping with the last
Open on LeetCode ↗

1Try it yourself first

00:00

Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.

Only for you, saved in this browser. After you see the approach you will compare it with your idea.

2What is being asked

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

How to recognise itA hash map gives O(1) insert/remove but cannot pick a random item; an array can pick a random item but cannot remove from the middle fast. Use both and swap with the last element.

3Hint ladder

Take one rung at a time. Stop as soon as the idea clicks.

  1. Hint 1
  2. Hint 2

4The approach

Have you tried the hints? The approach is built as a path from the obvious way to the clever one.

✓After you finish

Confidence