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).
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.
Problems using this pattern
3The SolutionRESULT → 2 or 3
Step through it
insert(1): append at the end, record its index → map{1: 0}
Step 1 / 5
Arrow keys to navigate · escape to reset