KatInterview

Mutable Integer Set with Freeze-Frame Iterators

Data Structure DesignModel answer
HardModel answerData Structure Designsnapshotsiteratorsappend-only log

Last 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

OperationBound
addO(1) amortized
removeO(1)
containsO(1)
freezeO(1)
has_next / nextO(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^5 total 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 intervening next().

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.