Implement command-driven in-memory key-value database
Company: Lyft
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design efficient in-memory data structures and implement transactional semantics for operations like SET/GET/DELETE/COUNT, including handling nested transactions, rollbacks, and commits.
Constraints
- 0 <= len(commands) <= 100000
- Keys and values are non-empty ASCII strings without whitespace
- The total number of key mutations across all commands is at most 100000
- Operations should be O(1) average/amortized, with ROLLBACK proportional to the number of reverted changes
Examples
Input: ([],)
Expected Output: []
Explanation: No commands produce no output.
Input: (["SET a 10", "SET b 10", "COUNT 10", "GET a", "DELETE a", "GET a", "COUNT 10", "DELETE missing", "COUNT 10"],)
Expected Output: ["2", "10", "NULL", "1", "1"]
Explanation: Two keys initially map to 10. After deleting a, GET a is NULL and only b still maps to 10. Deleting a missing key has no effect.
Hints
- Keep one hash map from key to value, and another hash map from value to the number of keys currently mapped to that value.
- For transactions, apply changes immediately but push the previous state of each changed key onto the current transaction's undo log. Roll back by replaying that log in reverse.