Tutorialspoint
Problem
Solution
Submissions

In-Memory Database with Transaction Support

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 20

Implement an in-memory key-value database system with support for nested atomic transactions.

Example 1
  • Input:
    db.set("a", 10)
    db.begin_transaction()
    db.set("a", 20)
    db.set("b", 30)
    db.commit()
    db.get("a"), db.get("b")
  • Output:
    20, 30
  • Explanation:
    • Start transaction.
    • Make changes to keys.
    • Commit makes changes permanent.
Example 2
  • Input:
    db.set("x", 100)
    begin → set x=200 → begin → set y=300 → rollback → rollback
  • Output:
    get("x") = 100
    get("y") = None
  • Explanation:
    • Rollback nested transactions step by step.
    • State returns to original after outer rollback.
Constraints
  • 1 ≤ key length ≤ 100
  • 0 ≤ operations ≤ 10^6
  • Supports string, number, boolean values
  • Time Complexity: O(1) average
  • Space Complexity: O(n + t)
Functions / MethodsDictionaries AmazonGoogle
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dictionaries to store the key-value pairs
  • Maintain a stack of transaction states
  • For each transaction, keep track of modified keys
  • When rolling back, revert only the keys modified in that transaction
  • For nested transactions, ensure changes in parent transactions are visible in child transactions

Steps to solve by this approach:

 Step 1: Create a class with a main data store and a transaction stack

 Step 2: Implement get method to search through transaction stack before falling back to main data
 Step 3: Implement set and delete methods to either modify the current transaction or main data
 Step 4: Implement begin_transaction to add a new empty transaction to the stack
 Step 5: Implement commit to apply all transaction changes to the main data store
 Step 6: Implement rollback to discard the most recent transaction

Submitted Code :