Implement in-memory database insert and delete operations
Company: OpenAI
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates understanding of data structures and algorithmic complexity in the context of designing a key-value in-memory database, and it falls under the Coding & Algorithms domain for a Machine Learning Engineer role while focusing on practical implementation skills.
Constraints
- 0 <= len(operations) <= 100000
- Each operation is one of ('insert', key, value), ('get', key), or ('delete', key)
- Each key is a non-empty string with length at most 50
- Each value is an integer in the range [-10^9, 10^9]
- Use a data structure with average O(1) insert, get, and delete
Examples
Input: [('insert', 'apple', 3), ('get', 'apple'), ('delete', 'apple'), ('get', 'apple')]
Expected Output: [3, True, None]
Explanation: After inserting 'apple' with value 3, get returns 3. Deleting 'apple' succeeds, so append True. A later get finds no such key, so append None.
Input: [('insert', 'x', 1), ('insert', 'x', 5), ('get', 'x'), ('delete', 'y'), ('get', 'y')]
Expected Output: [5, False, None]
Explanation: The second insert updates 'x' from 1 to 5. Getting 'x' returns 5. Deleting missing key 'y' returns False, and getting 'y' returns None.
Input: []
Expected Output: []
Explanation: No operations means no output. This checks the empty-input edge case.
Input: [('get', 'missing')]
Expected Output: [None]
Explanation: The key does not exist, so get returns None.
Input: [('insert', 'n', -7), ('insert', 'm', 2), ('delete', 'n'), ('get', 'n'), ('get', 'm'), ('delete', 'n')]
Expected Output: [True, None, 2, False]
Explanation: Deleting 'n' the first time succeeds. After that, get('n') returns None, get('m') returns 2, and deleting 'n' again fails.
Solution
def solution(operations):
db = {}
result = []
for op in operations:
action = op[0]
if action == 'insert':
_, key, value = op
db[key] = value
elif action == 'get':
_, key = op
result.append(db.get(key))
elif action == 'delete':
_, key = op
if key in db:
del db[key]
result.append(True)
else:
result.append(False)
else:
raise ValueError('Unknown operation')
return resultTime complexity: O(q) average, where q is the number of operations. Space complexity: O(k + r), where k is the number of keys stored and r is the number of returned results.
Hints
- A hash map (Python dictionary) supports average O(1) insert, lookup, and deletion by key.
- Process the operations from left to right and only append results for 'get' and 'delete'.