KatInterview

Simulate an In-Memory Key-Value Store

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designhash-tablesimulationdesign

Last updated

Tests ability to implement a command-driven key-value store with correct upsert, lookup, conditional update, delete, and membership semantics.

Problem

You are given a sequence of operations to run against an in-memory key-value store, starting empty. Each operation is a string, and each comes with a list of arguments. Process every operation in order and collect the return value of each one into a result list.

The store supports five operations:

put(key, value) Insert or overwrite the entry for key with value. Always returns None.

get(key) Return the value stored under key, or None if the key does not exist.

update(key, value) If key exists, replace its value with value and return True. If the key does not exist, do nothing and return False.

delete(key) If key exists, remove it and return True. If it does not exist, return False.

exists(key) Return True if key is currently in the store, False otherwise.

Return the list of results, one per operation, in the same order.

Constraints

  • 1 <= len(operations) == len(arguments) <= 1000
  • Every string in operations is one of: "put", "get", "update", "delete", "exists".
  • Keys are strings. Values may be any JSON-serializable type.
  • put and update receive two arguments; get, delete, and exists receive one.
  • put is the only operation that can create a new key. update must not create keys.
  • A key deleted by delete is fully gone; subsequent get returns None and exists returns False.
  • The store begins empty before the first operation.

Examples

Example 1

Input: run_kv_store(['put', 'get', 'exists', 'update', 'get', 'delete', 'get'], [['a', 1], ['a'], ['a'], ['a', 2], ['a'], ['a'], ['a']])

Output: [None, 1, True, True, 2, True, None]

Example 2

Input: run_kv_store(['put', 'put', 'get'], [['x', 'old'], ['x', 'new'], ['x']])

Output: [None, None, 'new']

Example 3

Input: run_kv_store(['get', 'update', 'delete', 'exists'], [['missing', ['v']], ['missing', 3], ['missing'], ['missing']])

Output: [None, False, False, False]

Hints

Hint 1

A plain dictionary is all the storage you need — every required operation maps directly to a dict method or membership test.

Hint 2

Distinguish `put` from `update` carefully: `put` is an unconditional upsert that always returns `None`, while `update` is a conditional write that returns a boolean and must never create a key.

Hint 3

Walk through a case where a key is put, then deleted, then read or updated — make sure your code returns the right values at each step rather than carrying stale state.