Problem · Design

Transactional Key-Value Store

Learn this problem
MediumGrammarly logoGrammarlyFULLTIMEONSITE INTERVIEW

Problem statement

Implement a key-value store that maps string keys to integer values and supports one active transaction at a time.

Process the finite ordered array operations. Each operation has one of these forms:

  • ["SET", key, value]: write value. Outside a transaction, the write immediately changes committed state. Inside a transaction, it changes only the transaction's private overlay.
  • ["GET", key]: read the transaction overlay first, then committed state. Return the value as a decimal string, or "null" when the key is missing.
  • ["BEGIN"]: start a transaction with an empty overlay. The input never contains BEGIN while a transaction is already active.
  • ["COMMIT"]: if a transaction is active, atomically apply all overlay writes to committed state, end the transaction, and return "true". Otherwise return "false".
  • ["ROLLBACK"]: if a transaction is active, discard all overlay writes, end the transaction, and return "true". Otherwise return "false".

SET and BEGIN do not produce output. Return the results of every GET, COMMIT, and ROLLBACK in encounter order.

Function

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

Examples

Example 1

operations = [["SET","item","1"],["GET","item"],["BEGIN"],["SET","item","2"],["GET","item"],["GET","missing"],["COMMIT"],["GET","item"]]return = ["1","2","null","true","2"]

The first read sees committed value 1. During the transaction, the overlay shadows it with 2, while an absent key returns null. Committing makes 2 the new committed value.

Example 2

operations = [["SET","balance","10"],["BEGIN"],["SET","balance","-5"],["GET","balance"],["ROLLBACK"],["GET","balance"],["COMMIT"]]return = ["-5","true","10","false"]

The transaction temporarily shadows balance with -5. Rolling it back restores the committed value 10. The final commit returns false because no transaction remains active.

Example 3

operations = [["BEGIN"],["SET","draft","7"],["GET","draft"],["ROLLBACK"],["GET","draft"],["SET","draft","9"],["GET","draft"]]return = ["7","true","null","9"]

The first write exists only in the active transaction, so rollback removes it. A later write outside a transaction is committed immediately.

Constraints

  • 1 <= operations.length <= 200000.
  • Every operation has exactly the form required by its command.
  • Keys contain from 1 through 64 lowercase English letters or digits.
  • Every value is the canonical decimal representation of a signed 32-bit integer.
  • BEGIN never occurs while a transaction is active.

More Grammarly problems

drafts saved locally
public String[] processTransactions(String[][] operations) {
  // write your code here
}
operations[["SET","item","1"],["GET","item"],["BEGIN"],["SET","item","2"],["GET","item"],["GET","missing"],["COMMIT"],["GET","item"]]
expected["1", "2", "null", "true", "2"]
checking account