Problem
FAANG · LeetCode #380

Insert Delete GetRandom O(1) — three-stage drill

1The ProblemMedium

Insert Delete GetRandom O(1)

A set supporting insert, remove, and uniform getRandom in O(1).

insert · remove · getRandom — all in O(1) averagearray[ a, b, c, … ]contiguous → O(1) random by indexmap{ value : index }→ O(1) find-and-remove (swap with last)array gives random;map gives lookupreturn2 or 3
Examples
insert,insert,remove,insert,getRandom→ 2 or 3

constraintAll three operations must be O(1) average; getRandom uniform.

2The PatternTIME O(n) · SPACE O(n)

Arrays & Hashing

Trade space for time: a hash map turns 'have I seen this?' into an O(1) lookup.

remember what you've seen in a hash map → O(1) lookup4021722344scan›value → countseen = {4: 1}
Problems using this pattern
3The SolutionRESULT → 2 or 3

Step through it

operationinsert(1)array10value → indexidx = {1: 0}
insert(1): append at the end, record its index → map{1: 0}
Step 1 / 5
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent