Problem · Hash Table

Nested Transaction Key-Value Store

Learn this problem
MediumxAI logoxAIFULLTIMEONSITE INTERVIEW

Problem statement

Process operations against an initially empty string key-value store.

  • ["SET", key, value] writes in the current transaction, or directly to the base store when no transaction is open.
  • ["GET", key] returns the most recent visible value, or NULL when absent.
  • ["BEGIN"] opens a transaction nested inside the current one.
  • ["COMMIT"] commits the innermost transaction into its parent, or into the base store when it is outermost.
  • ["ROLLBACK"] discards the innermost transaction.

An inner commit is not durable beyond its parent: if that parent is later rolled back, the inner changes disappear too. Return all GET outputs in order.

Function

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

Examples

Example 1

operations = [["SET","x","1"],["BEGIN"],["SET","x","2"],["BEGIN"],["SET","x","3"],["COMMIT"],["GET","x"],["ROLLBACK"],["GET","x"]]return = ["3","1"]

The inner commit makes x = 3 visible in its parent. Rolling back that parent then restores the base value x = 1.

Example 2

operations = [["BEGIN"],["SET","a","outer"],["BEGIN"],["SET","b","inner"],["GET","a"],["GET","b"],["COMMIT"],["COMMIT"],["GET","b"],["GET","missing"]]return = ["outer","inner","inner","NULL"]

The inner transaction reads its parent's a value. Committing both levels makes b visible in the base store.

Constraints

  • 1 <= operations.length <= 200000.
  • Every operation has the exact arity shown above.
  • COMMIT and ROLLBACK occur only while a transaction is open.
  • Keys and values are non-empty ASCII strings; values are never NULL.
  • The total length of all keys and values is at most 2000000.
  • Transaction nesting depth is at most 100000.

More xAI problems

drafts saved locally
public String[] runNestedTransactions(String[][] operations) {
    // Write your code here.
}
operations[["SET","x","1"],["BEGIN"],["SET","x","2"],["BEGIN"],["SET","x","3"],["COMMIT"],["GET","x"],["ROLLBACK"],["GET","x"]]
expected["3", "1"]
checking account