Mutable Integer Set with Freeze-Frame Iterators
Data Structure DesignModel answerLast updated
Design an integer set supporting O(1) add/remove/contains plus snapshot iterators that capture insertion-order state at creation time without copying.
Freeze-Frame Iterators
You are building a live integer set where readers and writers operate concurrently. Writers can add or remove elements at any time. Readers grab a "freeze-frame" iterator that walks the set exactly as it looked at the moment the iterator was created — later mutations are invisible to that reader.
Implement two classes, LiveSet and FreezeIterator:
class LiveSet:
def __init__(self):
pass
def add(self, val: int) -> bool:
"""Insert val. Return True if it was absent, False if already present."""
pass
def remove(self, val: int) -> bool:
"""Delete val. Return True if it was present, False if absent."""
pass
def contains(self, val: int) -> bool:
"""Return True if val is currently in the set."""
pass
def freeze(self) -> "FreezeIterator":
"""
Return an iterator over every element currently in the set,
in the order each was most recently inserted.
Must run in O(1) — no bulk copying allowed.
"""
pass
class FreezeIterator:
def has_next(self) -> bool:
"""True if unvisited elements remain in this snapshot. Idempotent."""
pass
def next(self) -> int:
"""Return the next element and advance the cursor. Raise StopIteration when exhausted."""
pass
Ordering rule
Elements appear in the order they were most recently inserted. If an element is removed and later re-added, its position moves to the end of the sequence as of that re-add.
Performance requirements
| Operation | Bound |
|---|---|
add | O(1) amortized |
remove | O(1) |
contains | O(1) |
freeze | O(1) |
has_next / next | O(1) amortized per call |
Example
s = LiveSet()
s.add(10)
s.add(20)
snap1 = s.freeze() # captures [10, 20]
s.remove(10)
s.add(30)
s.add(10) # 10 re-added — moves to end
snap2 = s.freeze() # captures [20, 30, 10]
# drain snap1
out1 = []
while snap1.has_next():
out1.append(snap1.next())
# out1 == [10, 20]
# drain snap2
out2 = []
while snap2.has_next():
out2.append(snap2.next())
# out2 == [20, 30, 10]
Constraints
- Integer values in
[-10^9, 10^9]. - At most
2 × 10^5total operations. - Multiple iterators may be alive simultaneously, advancing at different speeds, while mutations continue.
Edge cases to handle
freeze()called on an empty set.- An element removed before any iterator exists and never re-added.
- Multiple live iterators at different cursor positions when a mutation lands.
has_next()called several times in a row without an interveningnext().
Hints
Hint 1
A deep copy of the live set on every freeze() call is O(n) — too slow. Instead, think about what minimal information you need to reconstruct 'what was present at time T' later, using data you've already accumulated.
Hint 2
Consider an append-only log where every add() writes a new entry and remove() only annotates an existing entry rather than deleting it. A freeze-frame then becomes two integers: the log length and the current mutation counter at the moment of the call.
Hint 3
For each log entry, you need to answer: 'was this element alive at snapshot time T?' An element is alive in snapshot T if it was inserted before the snapshot's log boundary AND it had not yet been removed as of the snapshot's version. Store a removal-version stamp on each log entry; INF means still live.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Append-Only Log with Version Stamps
Core insight
The constraint that forbids bulk copying forces you to separate "recording what happened" from "replaying a past state on demand." The trick is an append-only log where every insertion creates a new record and every removal only annotates an existing record. A snapshot then costs O(1) to create — it is just two integers captured from the live set — and an iterator replays the relevant slice of the log lazily.
Data structures
_log: a list of[val, removed_at]records.removed_atstarts asINFand is set exactly once when the element is removed._pos: a dict from a live value to its index in_log. Gives O(1) lookup forcontainsandremove._version: an integer counter incremented on every successful mutation.
How each operation works
add(val) — if val is already in _pos, return False. Otherwise bump _version, append [val, INF] to _log, and record _pos[val] = len(_log) - 1. Re-adding a previously removed value creates a brand-new entry at the tail, which is exactly what the ordering rule requires.
remove(val) — pop val from _pos; if absent return False. Otherwise bump _version, write _log[idx][1] = _version, and return True. The record stays in the log forever (at least until garbage collection — see follow-ups).
contains(val) — val in _pos. One dict lookup.
freeze() — return FreezeIterator(log=_log, version=_version, end=len(_log)). No data is copied.
Iterator visibility rule
A log record at index i is visible to a snapshot (V, end) when both conditions hold:
i < end— the record was created before the snapshot_log[i][1] > V— the element had not been removed at the time of the snapshot (INF > Vmeans still live; a stamp<= Vmeans it was already gone)
has_next advances the cursor past invisible records and parks on the next visible one without consuming it. next calls has_next, reads the value, and increments the cursor. Because each index is examined at most once, the total work across the full lifetime of an iterator is O(end), so each call is O(1) amortized.
Correctness walkthrough
Using the example:
| Step | Log state | _version |
|---|---|---|
add(10) | [[10,∞]] | 1 |
add(20) | [[10,∞],[20,∞]] | 2 |
freeze() → snap1 | (V=2, end=2) | — |
remove(10) | [[10,3],[20,∞]] | 3 |
add(30) | [[10,3],[20,∞],[30,∞]] | 4 |
add(10) | [[10,3],[20,∞],[30,∞],[10,∞]] | 5 |
freeze() → snap2 | (V=5, end=4) | — |
snap1 (V=2, end=2) evaluates index 0: removed_at=3 > 2 ✓, index 1: ∞ > 2 ✓ → yields [10, 20].
snap2 (V=5, end=4) evaluates index 0: removed_at=3 > 5? No → skip. Index 1: ∞ > 5 ✓, index 2: ∞ > 5 ✓, index 3: ∞ > 5 ✓ → yields [20, 30, 10].
Common mistakes
- Bumping version on
addbut notremove(or vice versa). You need a single total order of mutations so the removal stamp is unambiguous relative to any snapshot. - Mutating
_poson re-add without creating a new log record. That destroys ordering: the old record's position is in the middle of the log, not at the tail. - Making
has_nextconsume the element. It must be idempotent; onlynextshould advance past the current element. - Using
dictinsertion order instead of an explicit log. Python 3.7+ dicts preserve insertion order but don't let you stamp removals in a way that's visible to past snapshots.
Complexity
| Time | Space | |
|---|---|---|
add / remove / contains / freeze | O(1) amortized | — |
| Full iterator traversal | O(end) total | O(1) extra per iterator |
| Overall space | — | O(total adds) |
Dead records accumulate, which is the main space trade-off. In a long-running system you'd garbage-collect entries whose removed_at stamp is less than or equal to the minimum version held by any live iterator.
Python implementation
from typing import Dict, List, Optional
INF = float("inf")
class FreezeIterator:
def __init__(self, log: List[list], version: int, end: int) -> None:
self._log = log # shared, never mutated in place (only appended)
self._v = version # snapshot version V
self._end = end # log boundary at freeze time
self._cur = 0 # cursor
def has_next(self) -> bool:
# Advance past records that are invisible to this snapshot.
log, v = self._log, self._v
while self._cur < self._end and log[self._cur][1] <= v:
self._cur += 1
return self._cur < self._end
def next(self) -> int:
if not self.has_next():
raise StopIteration
val = self._log[self._cur][0]
self._cur += 1
return val
class LiveSet:
def __init__(self) -> None:
self._log: List[list] = [] # [val, removed_at]
self._pos: Dict[int, int] = {} # live val -> log index
self._version: int = 0
def add(self, val: int) -> bool:
if val in self._pos:
return False
self._version += 1
self._pos[val] = len(self._log)
self._log.append([val, INF])
return True
def remove(self, val: int) -> bool:
idx = self._pos.pop(val, None)
if idx is None:
return False
self._version += 1
self._log[idx][1] = self._version
return True
def contains(self, val: int) -> bool:
return val in self._pos
def freeze(self) -> FreezeIterator:
return FreezeIterator(self._log, self._version, len(self._log))
Follow-up directions
Memory pressure. Dead records pile up. Track the minimum snapshot version across all live iterators (a version-count deque works because versions arrive in order). Any record whose removed_at <= min_version is invisible to everyone and can be reclaimed. Use a chunked array instead of a plain list so you can drop entire prefix chunks in O(1).
Bounding worst-case skip cost. A snapshot can land in a sea of dead records, making a single next() call walk many entries. One fix: on removal, write a versioned "skip pointer" into the predecessor record pointing past the removed entry. An iterator at version V follows the newest skip pointer whose version is ≤ V, jumping over dead runs in O(1).