← 返回 databricks 的题目列表Snapshot Set with Stable Iterators
类型:online_judge
Implement a SnapshotSet<T>:
interface SnapshotSet<T> {
void add(T e);
void remove(T e);
boolean contains(T e);
Iterator<T> iterator();
}
Requirements:
contains(e) queries membership in the current set.
iterator() returns an iterator over a snapshot of the set at the moment the iterator is created.
Any add/remove after an iterator is created must not affect what that iterator yields; however, it must affect contains and any iterators created later.
No ordering guarantee is required, but an iterator must not return duplicates and must not miss any element that belongs to its snapshot.
Implement add/remove/contains/iterator (Java or clear pseudocode). Also explain expected outputs for this scenario (order doesn’t matter, set contents do):
Start: add(5), add(2), add(8)
it = iterator() (created but not consumed)
remove(5), then contains(2) should be true
remove(2), then contains(2) should be false
add(2)
it2 = iterator()
it should iterate elements from the snapshot it captured; it2 should iterate elements from its own snapshot.
Note: The post suggests “snapshot set; old iterators must still be able to iterate.” Clarify with the interviewer whether this is a strong snapshot (fully isolated) or a weaker guarantee.
Example
Input
add 5
add 2
add 8
iter it
remove 5
contains 2
remove 2
contains 2
add 2
iter it2
consume it
consume it2
Output
contains(2)=true
contains(2)=false
it yields {5,2,8} (order arbitrary) if strong snapshot
it2 yields {2,8} (order arbitrary)