Design a Set with Numbered Snapshots and Sorted Snapshot Iterators

Quick Overview

Design a set that supports add, remove and membership checks along with numbered point-in-time snapshots, plus independent iterators that return a snapshot's elements in sorted order. It tests snapshot isolation from later writes, per-iterator state, and the time and memory cost of each method.

Design a Set with Numbered Snapshots and Sorted Snapshot Iterators

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a set data structure that supports point-in-time snapshots. The set should allow adding and removing elements, checking membership, and taking snapshots of its current state. After taking a snapshot, you can create an iterator that traverses the elements that existed in the set at the time the snapshot was taken, even if the live set has been modified afterward. Elements should be returned in sorted (ascending) order during iteration. Multiple iterators can be active simultaneously, and each operates independently over its respective snapshot. Implement the following methods: - `add(value: int)`: Add a value to the live set. If the value already exists, this is a no-op. - `remove(value: int) -> bool`: Remove a value from the live set. Returns `True` if the value was present and removed, `False` otherwise. - `contains(value: int) -> bool`: Check if the live set currently contains the given value. - `snap() -> int`: Take a snapshot of the current state of the set. Returns the `snap_id` (0-indexed, incrementing). - `iterator(snap_id: int) -> int`: Create an iterator over the elements that existed at the given snapshot. Returns an `iter_id`. - `hasNext(iter_id: int) -> bool`: Returns `True` if the iterator identified by `iter_id` has more elements. - `next(iter_id: int) -> int`: Returns the next element in sorted order from the iterator identified by `iter_id`. ```hint What a snapshot must freeze Once `snap()` returns, no later `add` or `remove` may change what that `snap_id` yields. Decide what each snapshot owns, and what an iterator has to remember on its own so that two iterators over the same snapshot never interfere. ``` ```hint Where the sorting cost goes You can sort when the snapshot is taken, when an iterator is created, or keep the elements ordered all along. Compare those choices against how often each method is likely to be called and how much memory each snapshot costs. ``` ### Examples #### Example 1 ```text Input: ["SnapshotSet", "add", "add", "add", "snap", "remove", "remove", "add", "iterator", "iterator", "next", "next", "next", "contains", "next", "hasNext", "hasNext"] [[], [5], [1], [3], [], [3], [3], [2], [0], [0], [0], [0], [1], [3], [0], [0], [1]] Output: [null, null, null, null, 0, true, false, null, 0, 1, 1, 3, 1, false, 5, false, true] Explanation: ss = SnapshotSet() # empty set ss.add(5) # live: {5} ss.add(1) # live: {1, 5} ss.add(3) # live: {1, 3, 5} ss.snap() # -> 0 (snapshot 0: [1, 3, 5]) ss.remove(3) # -> True (live: {1, 5}) ss.remove(3) # -> False (3 is no longer in the live set) ss.add(2) # live: {1, 2, 5} ss.iterator(0) # -> 0 (iterator 0 over snapshot 0) ss.iterator(0) # -> 1 (iterator 1 over snapshot 0) ss.next(0) # -> 1 ss.next(0) # -> 3 (removed from the live set, still in snapshot 0) ss.next(1) # -> 1 (iterator 1 has its own position) ss.contains(3) # -> False (contains checks the live set) ss.next(0) # -> 5 (2 was added after snapshot 0, so it never appears) ss.hasNext(0) # -> False ss.hasNext(1) # -> True (3 and 5 remain for iterator 1) ``` #### Example 2 ```text Input: ["SnapshotSet", "snap", "iterator", "hasNext", "add", "add", "snap", "contains", "iterator", "next", "next"] [[], [], [0], [0], [10], [20], [], [10], [1], [1], [1]] Output: [null, 0, 0, false, null, null, 1, true, 1, 10, 20] Explanation: ss = SnapshotSet() # empty set ss.snap() # -> 0 (snapshot 0: [], empty) ss.iterator(0) # -> 0 (iterator 0 over the empty snapshot) ss.hasNext(0) # -> False (nothing to iterate) ss.add(10) # live: {10} ss.add(20) # live: {10, 20} ss.snap() # -> 1 (snapshot 1: [10, 20]) ss.contains(10) # -> True ss.iterator(1) # -> 1 (iterator 1 over snapshot 1: [10, 20]) ss.next(1) # -> 10 ss.next(1) # -> 20 ``` ### Constraints & Assumptions - `1 <= value <= 10⁵` - `0 <= snap_id < number of snapshots taken so far` - At most `10⁴` calls in total will be made across all methods. - `iterator(snap_id)` is only called with valid `snap_id` values. - `next(iter_id)` is only called when `hasNext(iter_id)` is `True`. ### Clarifying Questions to Ask - Which pattern dominates: frequent snapshots of a large set, or many changes between rare snapshots? - Can callers release a snapshot or an iterator when they are done, so its memory can be reclaimed? - Will `add`, `remove`, `snap` and `next` be called from several threads at once? ### What a Strong Answer Covers - How a snapshot stays isolated from `add` and `remove` calls made after `snap()` returns. - Where the sorted order comes from and which method pays for it. - The state each iterator keeps so that several iterators over one snapshot advance independently. - Time per method and total memory as snapshots accumulate, with at least one way to reduce the memory. - Edge cases: an empty snapshot, a duplicate `add`, removing a missing value, and `snap()` with no changes since the previous one. ### Follow-up Questions - How would you make `snap()` run in `O(1)` when the set is large and snapshots are frequent? - How would you free the memory of snapshots that no iterator will read again? - How would the design change if `iterator()` took no argument and had to reflect the set at the moment it is created, while writes continue? - What locking would you add if several threads call `add`, `remove`, `snap` and `next` at the same time?

Overview: Design a set that supports add, remove and membership checks along with numbered point-in-time snapshots, plus independent iterators that return a snapshot's elements in sorted order. It tests snapshot isolation from later writes, per-iterator state, and the time and memory cost of each method.

PracHub logo
General
Nov 24, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a set data structure that supports point-in-time snapshots. The set should allow adding and removing elements, checking membership, and taking snapshots of its current state.

After taking a snapshot, you can create an iterator that traverses the elements that existed in the set at the time the snapshot was taken, even if the live set has been modified afterward. Elements should be returned in sorted (ascending) order during iteration.

Multiple iterators can be active simultaneously, and each operates independently over its respective snapshot.

Implement the following methods:

  • add(value: int) : Add a value to the live set. If the value already exists, this is a no-op.
  • remove(value: int) -> bool : Remove a value from the live set. Returns True if the value was present and removed, False otherwise.
  • contains(value: int) -> bool : Check if the live set currently contains the given value.
  • snap() -> int : Take a snapshot of the current state of the set. Returns the snap_id (0-indexed, incrementing).
  • iterator(snap_id: int) -> int : Create an iterator over the elements that existed at the given snapshot. Returns an iter_id .
  • hasNext(iter_id: int) -> bool : Returns True if the iterator identified by iter_id has more elements.
  • next(iter_id: int) -> int : Returns the next element in sorted order from the iterator identified by iter_id .

Examples

Example 1

Input:
["SnapshotSet", "add", "add", "add", "snap", "remove", "remove", "add", "iterator", "iterator", "next", "next", "next", "contains", "next", "hasNext", "hasNext"]
[[], [5], [1], [3], [], [3], [3], [2], [0], [0], [0], [0], [1], [3], [0], [0], [1]]

Output: [null, null, null, null, 0, true, false, null, 0, 1, 1, 3, 1, false, 5, false, true]

Explanation:
ss = SnapshotSet()      # empty set
ss.add(5)               # live: {5}
ss.add(1)               # live: {1, 5}
ss.add(3)               # live: {1, 3, 5}
ss.snap()               # -> 0      (snapshot 0: [1, 3, 5])
ss.remove(3)            # -> True   (live: {1, 5})
ss.remove(3)            # -> False  (3 is no longer in the live set)
ss.add(2)               # live: {1, 2, 5}
ss.iterator(0)          # -> 0      (iterator 0 over snapshot 0)
ss.iterator(0)          # -> 1      (iterator 1 over snapshot 0)
ss.next(0)              # -> 1
ss.next(0)              # -> 3      (removed from the live set, still in snapshot 0)
ss.next(1)              # -> 1      (iterator 1 has its own position)
ss.contains(3)          # -> False  (contains checks the live set)
ss.next(0)              # -> 5      (2 was added after snapshot 0, so it never appears)
ss.hasNext(0)           # -> False
ss.hasNext(1)           # -> True   (3 and 5 remain for iterator 1)

Example 2

Input:
["SnapshotSet", "snap", "iterator", "hasNext", "add", "add", "snap", "contains", "iterator", "next", "next"]
[[],            [],     [0],        [0],       [10],  [20],  [],     [10],       [1],        [1],    [1]]

Output: [null, 0, 0, false, null, null, 1, true, 1, 10, 20]

Explanation:
ss = SnapshotSet()      # empty set
ss.snap()               # -> 0      (snapshot 0: [], empty)
ss.iterator(0)          # -> 0      (iterator 0 over the empty snapshot)
ss.hasNext(0)           # -> False  (nothing to iterate)
ss.add(10)              # live: {10}
ss.add(20)              # live: {10, 20}
ss.snap()               # -> 1      (snapshot 1: [10, 20])
ss.contains(10)         # -> True
ss.iterator(1)          # -> 1      (iterator 1 over snapshot 1: [10, 20])
ss.next(1)              # -> 10
ss.next(1)              # -> 20

Constraints & Assumptions

  • 1 <= value <= 10⁵
  • 0 <= snap_id < number of snapshots taken so far
  • At most 10⁴ calls in total will be made across all methods.
  • iterator(snap_id) is only called with valid snap_id values.
  • next(iter_id) is only called when hasNext(iter_id) is True .

Clarifying Questions to Ask Guidance

  • Which pattern dominates: frequent snapshots of a large set, or many changes between rare snapshots?
  • Can callers release a snapshot or an iterator when they are done, so its memory can be reclaimed?
  • Will add , remove , snap and next be called from several threads at once?

What a Strong Answer Covers Guidance

  • How a snapshot stays isolated from add and remove calls made after snap() returns.
  • Where the sorted order comes from and which method pays for it.
  • The state each iterator keeps so that several iterators over one snapshot advance independently.
  • Time per method and total memory as snapshots accumulate, with at least one way to reduce the memory.
  • Edge cases: an empty snapshot, a duplicate add , removing a missing value, and snap() with no changes since the previous one.

Follow-up Questions Guidance

  • How would you make snap() run in O(1) when the set is large and snapshots are frequent?
  • How would you free the memory of snapshots that no iterator will read again?
  • How would the design change if iterator() took no argument and had to reflect the set at the moment it is created, while writes continue?
  • What locking would you add if several threads call add , remove , snap and next at the same time?