Simulate Snapshot Set Operations and Iterators
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate mutation and snapshot iteration on a persistent set structure using interval-based logical timestamps.
You are tasked with evaluating a data structure that implements a set of integers supporting $O(1)$ snapshot iterators.
The set maintains state across operations and supports:
add(n): Inserts integernif it is not currently present. ReturnsTrueif added, orFalseifnwas already present.remove(n): Deletes integernif it is currently present. ReturnsTrueif removed, orFalseifnwas not present.contains(n): ReturnsTrueifnis currently in the set, orFalseotherwise.getIterator(): Creates and returns a snapshot iterator freezing the exact set contents at the time of calling.
Behavioral & Snapshot Rules
- Logical Timestamping: A logical clock starts at $0$. Every successful modification (
addorremove) increments the clock by $1$. Operations that fail (e.g., adding an existing element or removing a missing element) do not increment the clock. - Lifespan Intervals: Each successful insertion creates a record
[value, insertion_clock, deletion_clock]. Thedeletion_clockis initiallyNone. When an element is successfully removed, its active record'sdeletion_clockis updated to the new clock value. If a previously removed element is re-added later, a brand new record is appended to history. - Snapshot Visibility: An iterator instantiated when the logical clock is $T$ views elements whose records satisfy: $$\text{insertion_clock} \le T \quad \text{and} \quad (\text{deletion_clock is None} \lor T < \text{deletion_clock})$$
- Iteration Order: Iterators traverse the set's historical insertion record array sequentially from index $0$ onward, skipping elements that fail the visibility condition for timestamp $T$.
- Iterator Independence: Iterators are independent and maintain their own index pointer into the set's history array. Modifications occurring after an iterator's creation do not affect its output.
Function Task
Implement snapshot_set_operations(operations, arguments) to process a list of commands and return a list of their respective results.
Supported operations in operations and their argument lists arguments:
"SnapshotSet": Arguments[]. Initializes a new empty set and clears all stored iterators. AppendsNone(rendered asnull) to the output."add": Arguments[n]. Callsadd(n). Appends the return boolean to the output."remove": Arguments[n]. Callsremove(n). Appends the return boolean to the output."contains": Arguments[n]. Callscontains(n). Appends the return boolean to the output."getIterator": Arguments[]. Spawns a new iterator viagetIterator(). Stores it in a dictionary indexed by incremental integer handles starting at0(0, 1, 2, ...). Appends the integer handle to the output."hasNext": Arguments[handle]. CallshasNext()on the iterator handle. Appends the boolean result to the output."next": Arguments[handle]. Callsnext()on the iterator handle. Appends the integer element, orNoneifStopIterationis raised."iterate": Arguments[handle]. Consumes all remaining elements from the iterator handle into a list and appends that list to the output.
Constraints
- $1 \le \text{len}(operations) \le 10^5$
len(operations) == len(arguments)- Element values fit in standard signed 32-bit integers.
Examples
Example 1
Input: snapshot_set_operations(['SnapshotSet', 'add', 'add', 'add', 'getIterator', 'remove', 'add', 'contains', 'iterate'], [[], [1], [2], [1], [], [1], [3], [1], [0]])
Output: [None, True, True, False, 0, True, True, False, [1, 2]]
Example 2
Input: snapshot_set_operations(['SnapshotSet', 'add', 'add', 'getIterator', 'getIterator', 'next', 'add', 'remove', 'iterate', 'iterate'], [[], [10], [20], [], [], [0], [30], [10], [0], [1]])
Output: [None, True, True, 0, 1, 10, True, True, [20], [10, 20]]
Example 3
Input: snapshot_set_operations(['SnapshotSet', 'getIterator', 'hasNext', 'next'], [[], [], [0], [0]])
Output: [None, 0, False, None]
Hints
Hint 1
Maintain a global logical timestamp (clock) that increments only on successful additions and deletions.
Hint 2
Track history entries as list elements of [value, insertion_time, deletion_time]. Store active entries in a key-to-entry map.
Hint 3
An iterator captured at timestamp T inspects history entries sequentially: an entry is valid if insertion_time <= T and (deletion_time is None or T < deletion_time).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The goal is to design a set data structure that can instantiate snapshot iterators in $O(1)$ time without making full copies of the set's underlying state.
1. Logical Clock & Timeline Log
- A logical integer clock (
_clock) tracks successful modifications. - Every successful
addincrements_clockand appends a record[val, insertion_time, deletion_time]to a central_historylist. - An auxiliary map
_activemaps each present value to its corresponding live record in_history. - A successful
removeincrements_clock, removes the entry from_active, and updates the record'sdeletion_timeto the current_clock.
2. Snapshot Iteration Mechanics
- Calling
getIterator()simply stores the current_clockvalue ($T$) and sets a starting index of0in $O(1)$ time. - When an iterator advances (
hasNext/next), it scans forward in_history. An entry is visible to snapshot $T$ if: $$\text{insertion_time} \le T \quad \text{and} \quad (\text{deletion_time is None} \lor T < \text{deletion_time})$$ - Elements outside this lifecycle range are bypassed. Scanning directly over
_historynaturally guarantees original insertion order.
Complexity Analysis
add(n): $O(1)$ amortized time.remove(n): $O(1)$ amortized time.contains(n): $O(1)$ average time.getIterator(): $O(1)$ time and space.hasNext()/next(): $O(1)$ amortized per iteration step across all entries in history.- Space Complexity: $O(N + M)$ total space, where $N$ is the number of insertion/deletion history records and $M$ is the number of active iterators.
Python 3 Reference Solution
from typing import List, Optional
class SnapshotIterator:
def __init__(self, owner, snapshot: int):
self._owner = owner
self._snapshot = snapshot
self._index = 0
def hasNext(self) -> bool:
history = self._owner._history
while self._index < len(history):
value, born, died = history[self._index]
if born <= self._snapshot and (died is None or self._snapshot < died):
return True
self._index += 1
return False
def next(self) -> int:
if not self.hasNext():
raise StopIteration
value = self._owner._history[self._index][0]
self._index += 1
return value
def __iter__(self):
return self
def __next__(self) -> int:
return self.next()
class SnapshotSet:
def __init__(self):
self._history = []
self._active = {}
self._clock = 0
def add(self, n: int) -> bool:
if n in self._active:
return False
self._clock += 1
entry = [n, self._clock, None]
self._history.append(entry)
self._active[n] = entry
return True
def remove(self, n: int) -> bool:
entry = self._active.pop(n, None)
if entry is None:
return False
self._clock += 1
entry[2] = self._clock
return True
def contains(self, n: int) -> bool:
return n in self._active
def getIterator(self) -> SnapshotIterator:
return SnapshotIterator(self, self._clock)
def snapshot_set_operations(operations: List[str], arguments: List[List[int]]) -> List[object]:
s = SnapshotSet()
iterators = {}
results = []
for op, args in zip(operations, arguments):
if op == 'SnapshotSet':
s = SnapshotSet()
iterators = {}
results.append(None)
elif op == 'add':
results.append(s.add(args[0]))
elif op == 'remove':
results.append(s.remove(args[0]))
elif op == 'contains':
results.append(s.contains(args[0]))
elif op == 'getIterator':
iterator = s.getIterator()
idx = len(iterators)
iterators[idx] = iterator
results.append(idx)
elif op == 'hasNext':
results.append(iterators[args[0]].hasNext())
elif op == 'next':
try:
results.append(iterators[args[0]].next())
except StopIteration:
results.append(None)
elif op == 'iterate':
results.append(list(iterators[args[0]]))
else:
raise ValueError('Unknown operation: ' + str(op))
return results