Link: https://leetcode.com/problems/insert-delete-getrandom-o1/
Solution:
Intuition
Great problem! I initially came up with an nlogn
solution using a SortedSet
, but the optimal o(1)
solution is very clever. I could have figured it out but I was pretty convinced that my SortedSet
solution was good enough so I didn’t push it. After reading the editorial, I regretted not taking this problem more seriously.
The concept is very simple: Keep a hash map that stores the indices of all elements added to a list. When it comes time to remove an element, index into it using the hash map and swap it with the last element in the list. Update the hash map and pop off the list!
So simple, but kind of subtle! Very nice in-place problem.
Implementation