Problem · Design

Snapshot Set Iterator

Learn this problem
MediumDatabricks logoDatabricksFULLTIMEPHONE SCREENONSITE INTERVIEW

Problem statement

Process a finite sequence of operations on an insertion-ordered set and its snapshot iterators.

Each operation is one of:

  • ["ADD", value]: add value when absent. Adding an existing value does nothing.
  • ["REMOVE", value]: remove value when present. Removing a missing value does nothing. A removed value that is later added again appears at the end of the insertion order.
  • ["ITERATOR", iteratorId]: create a new iterator over a snapshot of the current values in insertion order.
  • ["NEXT", iteratorId]: return the next value from that iterator, or "<END>" when it is exhausted.

Mutations after an iterator is created never change that iterator's snapshot. Return one string for every NEXT operation, in operation order.

Function

runSnapshotSet(operations: String[][]) → String[]

Examples

Example 1

operations = [["ADD","a"],["ADD","b"],["ITERATOR","it"],["ADD","c"],["REMOVE","a"],["NEXT","it"],["NEXT","it"],["NEXT","it"]]return = ["a","b","<END>"]

The iterator snapshots [a,b]. Adding c and removing a afterward do not affect it, so its two values are followed by the exhaustion sentinel.

Example 2

operations = [["ADD","x"],["ADD","y"],["ADD","x"],["REMOVE","x"],["ADD","x"],["REMOVE","z"],["ITERATOR","s"],["NEXT","s"],["NEXT","s"],["NEXT","s"]]return = ["y","x","<END>"]

The duplicate add and missing remove are no-ops. Removing and re-adding x moves it behind y in the current insertion order.

Constraints

  • 1 <= operations.length <= 10000
  • Every operation has a valid name and arity.
  • Values and iterator IDs are non-empty strings.
  • Values are never equal to "<END>".
  • Every iterator ID is created exactly once before its first NEXT.

More Databricks problems

drafts saved locally
public String[] runSnapshotSet(String[][] operations) {
    // Write your code here.
}
operations[["ADD","a"],["ADD","b"],["ITERATOR","it"],["ADD","c"],["REMOVE","a"],["NEXT","it"],["NEXT","it"],["NEXT","it"]]
expected["a", "b", "<END>"]
checking account