Practice/Databricks/SnapshotSet with Iterator
CodingMust
Design and implement a SnapshotSet<T> data structure that extends a standard set with snapshot-based iterators.
The key requirement is that iterators capture a read-only snapshot of the set at the time of their creation. These iterators remain immune to subsequent modifications (add/remove operations) performed on the set after the iterator is created.
add(x): Add element x to the set (no effect if already present)remove(x): Remove element x from the set (no effect if not present)contains(x): Return true if element x is currently in the setiterator(): Return an iterator over the current snapshot of the sethasNext() and next() methodsImportant: The contains() method always reflects the current state of the set, not any snapshot.
`
ss = SnapshotSet([1, 2, 3])
ss.add(4) # Set is now {1, 2, 3, 4}
iter1 = ss.iterator() print(iter1.next()) # Output: 1 print(iter1.next()) # Output: 2
ss.remove(3) # Set is now {1, 2, 4}
print(iter1.next()) # Output: 3 (still in snapshot!) print(iter1.next()) # Output: 4
iter2 = ss.iterator()
ss.add(6) # Set is now {1, 2, 4, 6}
print(iter2.next()) # Output: 1 print(iter2.next()) # Output: 2 print(iter2.next()) # Output: 4 print(iter2.hasNext()) # Output: False (6 not in snapshot)
print(ss.contains(3)) # Output: False (was removed) print(ss.contains(6)) # Output: True (was added) `
1 <= number of operations <= 10^5