FastPrepSnapshot Map with Sparse Version History
Problem · Design

Snapshot Map with Sparse Version History

Learn this problem
MediumSnorkel AI logoSnorkel AIFULLTIMEPHONE SCREEN

Problem statement

Implement a map that supports sparse immutable snapshots. Process the operations in order:

  • ["PUT", key, value] stores a current value.
  • ["GET", key] emits its current value, or "<NULL>".
  • ["DELETE", key] removes its current value.
  • ["SNAPSHOT"] captures the current state, emits the next zero-based snapshot ID, and then advances the ID.
  • ["GET_AT", key, snapshotId] emits the value captured for that key, or "<NULL>".

PUT and DELETE emit nothing. Repeating a PUT with the same current value or deleting a missing key must not add a version. If several mutations before the next snapshot restore a key to the value from the preceding snapshot, keep no entry for that transient change. Store only per-key changes rather than copying unchanged values into every snapshot. Return all emitted strings in operation order.

Function

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

Examples

Example 1

operations = [["PUT","a","red"],["SNAPSHOT"],["PUT","a","blue"],["GET","a"],["GET_AT","a","0"],["SNAPSHOT"],["GET_AT","a","1"]]return = ["0","blue","red","1","blue"]

Snapshot 0 keeps a=red. The later PUT changes only the current version and snapshot 1.

Example 2

operations = [["GET","x"],["PUT","x","1"],["DELETE","x"],["SNAPSHOT"],["GET_AT","x","0"]]return = ["<NULL>","0","<NULL>"]

The missing current lookup and the lookup after the delete both emit the null token.

Constraints

  • 1 <= operations.length <= 200000
  • Keys and values are non-empty printable ASCII strings without spaces.
  • Values are not equal to "<NULL>".
  • At most 1000000 distinct keys and 100000 snapshots occur.
  • Every GET_AT snapshot ID already exists.
drafts saved locally
public String[] runSnapshotMap(String[][] operations) {
  // Write your code here.
}
operations[["PUT","a","red"],["SNAPSHOT"],["PUT","a","blue"],["GET","a"],["GET_AT","a","0"],["SNAPSHOT"],["GET_AT","a","1"]]
expected["0", "blue", "red", "1", "blue"]
checking account