Design and implement a set data structure that supports snapshot iteration.
The set stores unique values. It must support the following operations:
-
add(value)
: Add
value
to the set if it is not already present.
-
remove(value)
: Remove
value
from the set if it is present. If it is absent, do nothing.
-
contains(value) -> bool
: Return whether
value
is 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
add
or
remove
must 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.