LeetCode #380 — Insert Delete GetRandom O(1)

David Seek
2 min readJun 13, 2020

Find more useful articles at www.davidseek.com

LeetCode’s challenge of the day on June 12, 2020 (#380) asks us to create an API wrapper around the standard Swift Set implementation. The only given requirement is that all operations must operate in constant time. We will use a Set as underlying data structure because there is no mentioning of duplication and all operations of a Set are constant by default.

insert(val) will forward to Set.insert and return a boolean indicating whether or not the given value has already been present in the underlying Set.

remove(val) will forward to Set.remove and return a boolean indicating whether or not the given value was inside the Set.

getRandom will return a random element from the underlying Set. There is no clear definition of what to return if the Set is empty yet the function declaration is does not return an optional value. So, we'll just return 0. This is a perfect example of missing clarification that you need to address in an interview.

If there is anything unclear or not clearly defined in the question statement, make sure to ask questions. Your interviewer will leave things out intentionally to trigger you to ask questions. The only mistake you can make here is to make assumptions and not be vocal about any uncertainty.

--

--