Implement Snapshot Iterator Without Order Guarantees
DatabricksSoftware Engineer · Technical ScreenLast updated
This question evaluates data-structure design and iterator semantics—specifically snapshot iteration over a mutable, set-like collection without order guarantees—and tests skills in implementing mutation-isolated iteration and analyzing time and space complexity; it belongs to the Coding & Algorithms domain and emphasizes practical implementation.
Design and implement a mutable collection that supports snapshot iteration.
The collection stores unique values and supports the following operations:
add(value): addvalueto the collection if it is not already present.remove(value): removevaluefrom the collection if it exists.contains(value): return whethervalueis currently in the collection.iterator(): return an iterator over a snapshot of the collection at the momentiterator()is called.
The snapshot iterator must satisfy:
- Later calls to
addorremovemust not change what the iterator returns. - Each element that existed in the collection when the iterator was created should be returned exactly once.
- The iterator does not need to preserve insertion order or any original data order.
- The iterator should expose standard methods such as
hasNext()andnext().
Implement the data structure and discuss the time and space complexity of each operation. Pay special attention to how the lack of ordering requirements affects your design.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.