Frozen-View Integer Set with Independent Cursors
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a mutable integer set whose iterators capture the set's contents at creation time and stay isolated from later changes and from each other.
Frozen-View Integer Set
You are simulating a mutable set of integers that can hand out iterators. Each iterator shows the set exactly as it was at the moment the iterator was created. Later changes to the set, and the progress of other iterators, never affect it.
You are given two lists of equal length. operations[i] is the name of the i-th command and arguments[i] is the list of arguments for that command. Process the commands in order. Every command appends exactly one entry to the output list.
| Operation | Arguments | Effect | Output entry |
|---|---|---|---|
add | [value] | Insert value into the set. Adding a value already present changes nothing. | None |
remove | [value] | Delete value from the set. Removing a value that is not present changes nothing. | None |
contains | [value] | Check whether value is currently in the set. | True or False |
iterator | [] | Create a new iterator that captures the current contents of the set. | The iterator's id: 0 for the first iterator created, 1 for the second, and so on |
hasNext | [iterator_id] | Check whether the iterator still has elements left to return. | True or False |
next | [iterator_id] | Return the next element of the iterator and advance it. If the iterator is exhausted, return None and do not advance. | The element, or None |
Iteration order
An iterator returns the elements of its captured contents in ascending numeric order, each exactly once.
Details
- Each iterator has its own position. Advancing one iterator never moves another, even if they were created when the set had identical contents.
- An iterator is unaffected by any
addorremoveperformed after it was created, including those that happen midway through its traversal. - An iterator created on an empty set has
hasNextequal toFalseandnextequal toNone. - Repeated
nextcalls on an exhausted iterator keep returningNone. - Iterator ids passed to
hasNextandnextalways refer to iterators that have already been created.
Return the list of output entries, one per command, in order.
Constraints
len(operations) == len(arguments)- The set holds at most 10^5 elements at any time.
- Values are integers.
operationis always one ofadd,remove,contains,iterator,hasNext,next.add,remove, andcontainsshould run in O(1) average or O(log N) time.
Examples
Example 1
Input: simulate_frozen_set(['add', 'add', 'iterator', 'add', 'remove', 'next', 'next', 'hasNext'], [[1], [2], [], [3], [1], [0], [0], [0]])
Output: [None, None, 0, None, None, 1, 2, False]
Example 2
Input: simulate_frozen_set(['iterator', 'hasNext', 'next', 'hasNext'], [[], [0], [0], [0]])
Output: [0, False, None, False]
Example 3
Input: simulate_frozen_set(['add', 'add', 'iterator', 'iterator', 'remove', 'next', 'next', 'next', 'next'], [[5], [1], [], [], [5], [0], [1], [0], [1]])
Output: [None, None, 0, 1, None, 1, 1, 5, 5]
Hints
Hint 1
Keep two separate pieces of state: a live set for add, remove, and contains, and a per-iterator record for traversal.
Hint 2
When an iterator is created, copy the current contents into a sorted list and pair it with a cursor index. Later changes touch only the live set, so the copy never changes.
Hint 3
Use discard rather than remove on a Python set so that removing a missing value is a no-op, and only advance the cursor in next when elements remain.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are two separate concerns, so we keep two kinds of state.
- The live set. A Python
sethandlesadd,remove, andcontainsin O(1) average time. We usediscardfor removal so that deleting a missing value is a harmless no-op. - The iterators. When
iteratoris called, we build a brand-new sorted list from the live set and pair it with a cursor starting at 0. This pair is stored in a dictionary under the next iterator id (0, 1, 2, ...).
hasNext checks whether the cursor is still inside the list. next returns the element at the cursor and advances it, or returns None without moving if the list is exhausted.
Why it is correct
- Snapshot isolation.
sorted(live)creates a new list that no other code writes to. Its contents equal the set at the instant the iterator was created. Lateraddandremovecalls modify only the live set. - Independent iterators. Every id maps to its own list and its own cursor, so advancing one iterator cannot affect another, even if both were created from identical states.
- Ascending order. Sorting at creation time gives the required deterministic order.
- Edge cases. An empty set yields an empty list, so
hasNextisFalseandnextisNone. Duplicate adds are no-ops because of set semantics. Repeatednextcalls after exhaustion returnNoneand leave the cursor unchanged.
Complexity
Let N be the size of the set at the time of the call.
add,remove,contains: O(1) average time.iterator: O(N log N) time and O(N) extra space for that iterator.hasNext,next: O(1) time.- Total space: O(N plus the sum of all snapshot sizes).
Possible improvements
If the memory cost per iterator matters, an iterator can instead record only a version number, with each value storing the version intervals during which it was present. Another option is a persistent balanced tree, where a snapshot is just a root pointer and each mutation copies O(log N) nodes. The simple copy shown here is the easiest to get right and fits the stated limits.
Reference solution
from typing import List
def simulate_frozen_set(operations: List[str], arguments: List[List[int]]) -> List[object]:
live = set()
views = {}
next_id = 0
output = []
for op, args in zip(operations, arguments):
if op == "add":
live.add(args[0])
output.append(None)
elif op == "remove":
live.discard(args[0])
output.append(None)
elif op == "contains":
output.append(args[0] in live)
elif op == "iterator":
views[next_id] = [sorted(live), 0]
output.append(next_id)
next_id += 1
elif op == "hasNext":
items, pos = views[args[0]]
output.append(pos < len(items))
elif op == "next":
view = views[args[0]]
items, pos = view
if pos >= len(items):
output.append(None)
else:
output.append(items[pos])
view[1] += 1
else:
raise ValueError(f"unknown operation: {op}")
return output