Problem · Hash Table

Nested In-Memory Database Transactions

Learn this problem
MediumDRW logoDRWFULLTIMEOA

Problem statement

Implement an in-memory database with a permanent store and a stack of active transactions. Process the finite array operations from left to right and return one output string for every operation.

Each operation has one of these forms:

  • BEGIN: push an empty transaction and return OK.
  • SET key value: write into the newest active transaction and return OK. If no transaction is active, do not change state and return ERROR.
  • GET key: search active transactions from newest to oldest, then the permanent store. Return the first value found, or NOT_FOUND.
  • COUNT: return the number of keys in the permanent store as a decimal string. Uncommitted keys do not count.
  • ROLLBACK: discard only the newest active transaction and return OK. If no transaction is active, return ERROR.
  • COMMIT: apply all active transactions to the permanent store from oldest to newest, clear the transaction stack, and return OK. If no transaction is active, return ERROR.

The database starts with an empty permanent store and no active transaction.

Function

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

Examples

Example 1

operations = ["COUNT","BEGIN","SET a 1","GET a","COUNT","COMMIT","COUNT","GET a"]return = ["0","OK","OK","1","0","OK","1","1"]

The uncommitted key is readable through GET but does not affect COUNT. After COMMIT, it becomes permanent.

Example 2

operations = ["BEGIN","SET x outer","BEGIN","SET x inner","GET x","ROLLBACK","GET x","COMMIT","GET x"]return = ["OK","OK","OK","OK","inner","OK","outer","OK","outer"]

The inner value shadows the outer value until the inner transaction is rolled back. Committing then makes the outer value permanent.

Constraints

  • Every operation follows one of the documented command forms.
  • Keys and values are non-empty and contain no whitespace.
  • A stored value is never the reserved result token NOT_FOUND.

More DRW problems

drafts saved locally
public String[] runDatabaseSimulator(String[] operations) {
    // Write your code here.
}
operations["COUNT","BEGIN","SET a 1","GET a","COUNT","COMMIT","COUNT","GET a"]
expected["0", "OK", "OK", "1", "0", "OK", "1", "1"]
checking account