Implement a Snapshot Set Iterator
DatabricksSoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of set data structures, iterator and snapshot semantics, and the ability to reason about time and space complexity when providing stable views over mutable collections.
Design and implement a set data structure that supports snapshot iteration.
The set stores unique values. It must support the following operations:
add(value): Addvalueto the set if it is not already present.remove(value): Removevaluefrom the set if it is present. If it is absent, do nothing.contains(value) -> bool: Return whethervalueis currently in the set.iterator(): Return an iterator over a snapshot of the set at the moment the iterator is created.
Snapshot iterator requirements:
- The iterator should return exactly the values that were present in the set when the iterator was created.
- Later calls to
addorremovemust not affect already-created iterators. - The return order of values is not important.
- Each value in the snapshot should be returned exactly once.
Example:
s = SnapshotSet()
s.add(1)
s.add(2)
it = s.iterator()
s.remove(1)
s.add(3)
# The iterator should still return 1 and 2 in any order.
# It should not return 3.
Implement the data structure and iterator. Discuss the time and space complexity of your approach.
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.