Point-in-Time Set Views from an Operation Log
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a set that processes add, remove, contains and snapshot operations, where each snapshot must be an independent frozen copy of the set at that moment.
You are simulating a set of integers that can hand out frozen, point-in-time views of itself.
The set starts empty. You receive two parallel lists, operations and arguments. The operation at index i is operations[i], and its parameters are arguments[i]. Apply the operations in order. Each one produces exactly one entry in the output list.
Operations
| Operation | Arguments | Effect | Output entry |
|---|---|---|---|
"add" | [x] | Insert x if it is not already in the set. | None |
"remove" | [x] | Delete x if it is in the set. Otherwise do nothing. | None |
"contains" | [x] | Check whether x is currently in the set. | True or False |
"iterator" | [] | Take a snapshot of the set as it is right now. | A list of the snapshot's values |
Snapshot rules
- A snapshot holds exactly the values that were in the set when the
"iterator"operation was processed, each one once. - Later
"add"and"remove"operations must never change a snapshot that was already produced. - Snapshots are independent of each other and of the live set.
- An empty set produces
[].
Order of values inside a snapshot
Conceptually the order of a snapshot does not matter, but the output is compared as a plain list, so the order must be reproduced exactly. Keep the live values in a built-in Python set, updated with set.add for "add" and set.discard for "remove" in operation order. A snapshot is the result of list(live_set) taken at that moment. Do not sort the values.
Task
Return the list of output entries, one per operation, in the same order as operations.
Constraints
len(operations) == len(arguments), and both lists have between 0 and 10^4 entries.- Every operation name is one of
"add","remove","contains","iterator". "add","remove"and"contains"have exactly one integer argument."iterator"has an empty argument list.- Integer arguments fit in a signed 32-bit integer.
- Adding a value that is already present, or removing one that is absent, is a no-op and is not an error.
Examples
Example 1
Input: run_snapshot_set_ops(['add', 'add', 'iterator', 'remove', 'add', 'iterator'], [[1], [2], [], [1], [3], []])
Output: [None, None, [1, 2], None, None, [2, 3]]
Example 2
Input: run_snapshot_set_ops(['add', 'contains', 'remove', 'contains', 'iterator'], [[5], [5], [9], [9], []])
Output: [None, True, None, False, [5]]
Hints
Hint 1
Start with the simplest correct model: keep a hash set for the live values and decide what an 'iterator' operation should record.
Hint 2
A snapshot must not share mutable state with the live set. Think about what you must copy, and when, so later adds and removes cannot leak in.
Hint 3
Build each snapshot as a brand-new list from the live set at that moment. Do not reorder it, because the expected output uses the set's own iteration order. Copying costs O(n) per snapshot; versioning each stored occurrence with an (added, removed) range is the idea for O(1) snapshot creation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a built-in hash set of the values currently present, and process the operations one at a time.
addinserts into the set. Inserting an existing value does nothing.removeusesdiscard, so removing an absent value does nothing.containsis a hash lookup.iteratorbuilds a new list withlist(live). Because it is a fresh list, nothing that happens to the live set afterwards can change it. The list is not sorted, so its order matches the set's own iteration order.
Why it is correct
A snapshot is created at the instant its iterator operation is processed, so it holds exactly the values present at that moment. It shares no mutable state with the live set, so later add and remove calls cannot affect it. Each value appears once because the underlying structure is a set. Applying the same add and discard calls in the same order reproduces the same iteration order as the expected output.
Complexity
add,remove,contains: O(1) average.iterator: O(n) to copy, where n is the current set size.- Space: O(n) for the live set, plus O(n) for each snapshot returned.
Going further
In a real iterator-based design, copying on every iterator() call is wasteful, especially if the caller reads only a few elements. A stronger design makes iterator creation O(1) with versioning:
- Keep a global version counter that increases on every effective mutation.
- Store each occurrence of a value as an entry with
addedandremovedversions (removedis infinity while the value is live). A value that is removed and re-added gets a new entry. - An iterator remembers only the log length and the version at creation. It yields entries that were added at or before that version and not removed until after it.
- To bound memory, occasionally replace the log with a new list of live entries. Do not mutate the old list, since existing iterators still reference it.
Another option is copy-on-write: share the underlying set between snapshots and clone it lazily on the first mutation after a snapshot.
Reference solution
from typing import List
def run_snapshot_set_ops(operations: List[str], arguments: List[List[int]]) -> List[object]:
live = set()
results = []
for op, args in zip(operations, arguments):
if op == "add":
live.add(args[0])
results.append(None)
elif op == "remove":
live.discard(args[0])
results.append(None)
elif op == "contains":
results.append(args[0] in live)
elif op == "iterator":
# list() builds a brand-new list, so the snapshot is independent
results.append(list(live))
else:
raise ValueError("Unknown operation")
return results