Problem · Design

KV Store with Nested Transactions

MediumApplied IntuitionFULLTIMEPHONE SCREEN

Implement an in-memory key-value store that supports nested transactions. Commands are executed in order, one command per line.

Supported commands are:

  • SET <key> <value>
  • GET <key>
  • DELETE <key>
  • BEGIN
  • ROLLBACK
  • COMMIT

GET returns the current value of a key, or NULL if it does not exist. ROLLBACK and COMMIT print NO TRANSACTION when there is no active transaction.

Return the lines that would be printed while processing the command batch.

Function Description

Complete the function runNestedTransactions in the editor below.

runNestedTransactions has the following parameter:

  1. String[] commands: the command batch, one command per element

Returns

String[]: the output lines produced by the batch in order.

Examples
01 · Example 1
commands = ["SET a 10", "GET a"]
return = ["10"]

After setting a to 10, GET a prints that value.

02 · Example 2
commands = ["SET a 10", "BEGIN", "SET a 20", "BEGIN", "DELETE a", "GET a", "ROLLBACK", "GET a", "COMMIT", "GET a"]
return = ["NULL", "20", "20"]

The inner transaction deletes a, so the first GET prints NULL. After rolling back the inner transaction, a becomes 20 again. Committing keeps that value permanent.

Constraints
  • 1 <= commands.length <= 200000
  • Keys and values are non-empty strings without spaces.
  • Transactions may be nested arbitrarily deeply.
  • A near-linear total runtime is expected for large command batches.
More Applied Intuition problems
drafts saved locally
public String[] runNestedTransactions(String[] commands) {
    // write your code here
}
commands["SET a 10", "GET a"]
expected["10"]
sign in to submit