Versioned Membership Tracker with Point-in-Time Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests ability to design a copy-on-write set that records per-element change history and answers historical membership queries in O(log n) via binary search.
Overview
You are building a collection that tracks unique integers over time. Instead of copying the whole collection whenever you take a checkpoint, the structure records only what changed and reconstructs past states on demand.
You will process a sequence of named operations driven by a driver function. Each operation is one of the six types described below.
Operations
add(val)
Insert val into the collection. Return True if val was absent and was successfully inserted. Return False if val was already present (no change is made).
remove(val)
Delete val from the collection. Return True if val was present and was removed. Return False if val was not present (no change is made).
contains(val)
Return True if val is currently in the collection, False otherwise.
snapshot()
Freeze the current state of the collection as a numbered checkpoint and return its id. The first call returns 0, the second returns 1, and so on. Checkpoint creation must be O(1) — do not copy the entire collection.
contains_at(snapshot_id, val)
Return True if val was present in the collection at the moment checkpoint snapshot_id was taken, False otherwise. Raise IndexError if snapshot_id is negative or greater than or equal to the total number of checkpoints taken so far.
Driver Interface
Implement the function:
def versioned_set_ops(operations: List[str], arguments: List[List[int]]) -> List[object]:
operations: a list of operation name strings.arguments: parallel list of argument lists. Operations that take no arguments use an empty list[].- Return a list containing the return value of each operation in order.
Constraints
- Total operations: up to
2 × 10^5. - Element values:
-10^9 ≤ val ≤ 10^9. - A valid
snapshot_idsatisfies0 ≤ snapshot_id < (number of snapshots taken so far). Anything outside this range must raiseIndexError. - Multiple add/remove calls on the same element within the same checkpoint interval must not produce redundant history entries — only the final state before the next checkpoint matters.
- The collection starts empty. No checkpoint exists until the first
snapshot()call.
Examples
Example 1
Input: versioned_set_ops(['add', 'add', 'snapshot', 'remove', 'add', 'snapshot', 'contains', 'contains_at', 'contains_at', 'contains_at', 'contains_at'], [[1], [2], [], [1], [3], [], [1], [0, 1], [1, 1], [0, 3], [1, 3]])
Output: [True, True, 0, True, True, 1, False, True, False, False, True]
Example 2
Input: versioned_set_ops(['snapshot', 'contains_at', 'add', 'snapshot', 'remove', 'snapshot', 'contains_at'], [[], [0, 7], [7], [], [7], [], [2, 7]])
Output: [0, False, True, 1, True, 2, False]
Hints
Hint 1
Instead of copying the whole collection each checkpoint, think about what minimal information you need to record per element — specifically, the moments when its membership status actually flips.
Hint 2
For each element, maintain a list of (epoch, is_present) pairs in chronological order. A checkpoint ID is just an epoch boundary. To answer a historical query, you need the last recorded event at or before that epoch — binary search is a natural fit.
Hint 3
When multiple mutations affect the same element within the same epoch, only the final state is observable at checkpoint time. Overwrite the last history entry instead of appending when its epoch matches the current one, keeping the list compact.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight: record changes, not copies
Copying the entire collection on every snapshot() call costs O(n) per checkpoint. The key observation is that a snapshot only needs to capture what changed. If an element's membership status hasn't flipped since the last checkpoint, you don't need to record anything new for it.
The structure maintains two things:
current: a plain Pythonsetthat answersadd,remove, andcontainsin O(1).history: a dictionary mapping each element value to a list of(epoch, is_present)pairs in strictly increasing epoch order. Each pair records the element's membership status at the end of a particular epoch.
A global counter epoch starts at 0. All mutations that happen while epoch == k belong to epoch k. When snapshot() is called, it returns the current epoch and increments it. Subsequent mutations fall into epoch k + 1.
Collapsing redundant changes within one epoch
Only the state at the end of an epoch is visible to a checkpoint. If two mutations affect the same element within the same epoch (add then remove, or remove then add), only the final state matters. To enforce this, whenever we record a change we check whether the last entry in that element's history list already has epoch == current_epoch. If so, we overwrite it in place rather than appending. This keeps each element's list compact and makes the binary search unambiguous.
Answering contains_at(snapshot_id, val)
We need the last recorded event for val with event_epoch <= snapshot_id. Its is_present flag is the answer. If no such event exists, the element had never been added by that checkpoint, so the answer is False.
bisect_right(events, (snapshot_id, True)) - 1 finds exactly this:
- Python compares tuples lexicographically.
Truesorts afterFalse, so(snapshot_id, True)is larger than both(snapshot_id, False)and(snapshot_id, True)itself —bisect_rightsteps past both.- The index returned is the count of events with
epoch <= snapshot_id; subtract one to get the last such event. - An index of
-1means no prior event exists → returnFalse.
Why this is correct end to end
- Each element's history list is a complete log of real state changes, one entry per epoch at most.
- The last entry at or before epoch
scaptures the element's state exactly when checkpointswas taken. - No mutation between that event and the snapshot can affect the answer, because any such mutation would have been recorded in the same epoch and would have overwritten that entry.
Edge cases
- Querying a value that was never added returns
False—history.getreturns an empty list and the index is-1. - An invalid
snapshot_id(negative, or ≥ the number of snapshots taken) raisesIndexError. contains_atbefore anysnapshot()call always raisesIndexErrorbecauseepoch == 0and no valid id exists yet.- A no-op
add(element already present) or no-opremove(element absent) returnsFalseand writes nothing to history. - A
snapshot()with no changes since the previous one costs nothing and still inherits all earlier events for correct lookups. - Negative and large values (±10^9) need no special handling — they are hashed, not used as indices.
Complexity
| Operation | Time | Notes |
|---|---|---|
add / remove | O(1) amortized | set update + append or in-place overwrite |
contains | O(1) average | plain set lookup |
snapshot | O(1) | integer increment only |
contains_at | O(log K) | binary search over that value's K history entries |
Space is O(U + E), where U is the number of distinct values ever seen and E is the total number of real state changes. Both are bounded by the total number of operations, at most 2 × 10^5.
Reference solution
from bisect import bisect_right
from typing import List
def versioned_set_ops(operations: List[str], arguments: List[List[int]]) -> List[object]:
current = set() # live membership for O(1) add/remove/contains
history = {} # val -> [(epoch, is_present), ...] strictly increasing epoch
epoch = 0 # current epoch; equals number of snapshots taken so far
results = []
for operation, args in zip(operations, arguments):
if operation == "add":
val = args[0]
changed = val not in current
if changed:
current.add(val)
events = history.setdefault(val, [])
if events and events[-1][0] == epoch:
events[-1] = (epoch, True) # collapse within same epoch
else:
events.append((epoch, True))
results.append(changed)
elif operation == "remove":
val = args[0]
changed = val in current
if changed:
current.remove(val)
events = history.setdefault(val, [])
if events and events[-1][0] == epoch:
events[-1] = (epoch, False) # collapse within same epoch
else:
events.append((epoch, False))
results.append(changed)
elif operation == "contains":
results.append(args[0] in current)
elif operation == "snapshot":
results.append(epoch)
epoch += 1
elif operation == "contains_at":
snapshot_id, val = args
if snapshot_id < 0 or snapshot_id >= epoch:
raise IndexError("invalid snapshot_id")
events = history.get(val, [])
# Find the last event with event_epoch <= snapshot_id.
# bisect_right on (snapshot_id, True) works because True > False,
# so it steps past any (snapshot_id, False) entry as well.
index = bisect_right(events, (snapshot_id, True)) - 1
results.append(index >= 0 and events[index][1])
else:
raise ValueError(f"unknown operation: {operation}")
return results