The Runtime Theory
mediumLeetCode#hash-map#dynamic-array

Insert Delete GetRandom O(1)

Implement unique insert, delete, and uniform random selection in expected constant time.

The Runtime Theory Team25 min read
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ininsert(1), remove(2), insert(2), getRandom()

outreturned value belongs to {1,2}; each is equally likely

ininsert(1), remove(1), insert(1)

outtrue

instructure contains [4,8,9], getRandom()

outreturned value is one of {4,8,9}

Implement unique insert, delete, and uniform random selection in expected constant time.

A good solution should

  • State the invariant or decision rule that makes the approach correct.
  • Explain time and space costs in terms of input size and required output.
  • Handle empty, minimal, duplicate, and boundary-shaped inputs.

Reasoning prompt

Use an array plus value-to-index map. Delete by swapping with the final element and updating the moved value’s index.

Use the linked judge for the canonical challenge. The examples above are compact TRT checks; create additional tests around the boundary most likely to break your invariant.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.

Not started

Sign in to save your learning progress.

Sign in to save