KatInterview

Design a Custom Key-Value Map

Data Structure DesignAuto-graded · 15 test cases
HardAuto-gradedData Structure Designarraysdesign-dshash-table

Last updated

Execute a series of map operations (put, get, remove) by simulating a hash map without using built-in dictionaries or sets.

Design and simulate a custom key-value store class from scratch without using any standard language map, dictionary, or set data structures.

The underlying implementation must handle collision resolution and dynamic resizing. The operations to process are given as two synchronized lists: operations (specifying the method to execute) and arguments (the parameter list for each operation).

The custom key-value store must support three primary operations:

  • put(key, value): Inserts or updates the given key with value. Returns None.
  • get(key): Retrieves the value associated with key. If the key is not found, returns None.
  • remove(key): Deletes the key-value pair associated with key and returns the removed value. If the key is not present, returns None.

Given a sequence of operations and their corresponding arguments, simulate the behavior of the hash map and return a list containing the output of each operation in order.

Constraints

  • $1 \le \text{len(operations)} \le 10^4$
  • len(operations) == len(arguments)
  • operations[i] is one of "put", "get", or "remove".
  • arguments[i] contains the appropriate arguments for the corresponding operation:
    • For "put": [key, value]
    • For "get": [key]
    • For "remove": [key]
  • Keys can be integers, strings, or any hashable type.
  • Values can be of any data type.
  • Do not use built-in dict or set types in your custom data structure implementation.

Output Format

Return a list of results corresponding to each operation in operations. For operations that return None (such as put or failing lookups/removals), include None in the output list.

Examples

Example 1

Input: key_value_store(['put', 'get', 'put', 'get', 'remove', 'get'], [['apple', 3], ['apple'], ['apple', 8], ['apple'], ['apple'], ['apple']])

Output: [None, 3, None, 8, 8, None]

Example 2

Input: key_value_store(['put', 'put', 'get', 'remove'], [[1, 'one'], [2, 'two'], [2], [1]])

Output: [None, None, 'two', 'one']

Example 3

Input: key_value_store(['put', 'put', 'get', 'get'], [['a', None], ['b', 0], ['a'], ['b']])

Output: [None, None, None, 0]

Hints

Hint 1

Collision handling can be implemented using separate chaining with raw lists inside fixed-capacity buckets.

Hint 2

Track the number of unique elements inserted and trigger a resize (e.g., doubling bucket count) when the load factor threshold is reached.

Hint 3

For string or integer keys, use Python's built-in `hash()` modulo the bucket count to compute bucket indices.