Skip to content

visual walkthrough

Insert Delete GetRandom O(1)

MediumHash Map + ArrayReported at: MetaAmazonMicrosoft+5

Combining two structures to get O(1) for everything; a top design question.

Solve on LeetCode

The idea

A hash map gives O(1) insert and delete but can't pick a random element; an array can pick a random element but is slow to delete from the middle. Keep both.

To delete in O(1), copy the last element over the one being removed, update its index in the map, and pop the end. Order doesn't matter, so nothing needs shifting.

Complexity

approachtimespace
Array onlyO(n) removeO(n)
Array + mapO(1) eachO(n)

More walkthroughs