KatInterview

Design a Recency-Tracking Key-Value Store

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designdesign-dslinked-listsarrays

Last updated

Simulate operations on a custom key-value map that efficiently queries the most recently updated active entry.

Design an in-memory key-value container supporting insertion, value retrieval, key deletion, and querying the value of the most recently inserted or modified active key.

Implement a function process_store_operations that takes a sequence of operation names and their corresponding arguments, executes them in order, and returns a list containing the output of each operation.

Supported Operations

  1. "add": Takes [key, value].

    • Inserts the key-value pair if the key does not exist.
    • If the key already exists, updates its value and moves it to the most recent position.
    • Output: None.
  2. "get": Takes [key].

    • Returns the stored value associated with key, or None if the key is not present.
    • Performing a "get" operation does not change the recency of the key.
    • Output: The value or None.
  3. "remove": Takes [key].

    • Deletes the key and its value from the store.
    • If the key does not exist, no action is taken.
    • Output: None.
  4. "getLast": Takes [].

    • Returns the value of the most recently added or updated key currently present in the store.
    • If the store is empty, returns None.
    • Output: The value or None.

Constraints

  • operations is a list of strings where each element is one of "add", "get", "remove", or "getLast".
  • arguments is a list of lists matching operations in length and argument format.
  • Keys are strings or integers, and values are integers.
  • All operations should execute efficiently.

Edge Case Rules

  • Updating an existing key refreshes its recency so that it becomes the most recent element.
  • Removing the current most recent element makes the previously most recent active element the new most recent.
  • Removing non-existent keys is a non-op and must not alter the structure or recency tracking.

Examples

Example 1

Input: process_store_operations(['add', 'add', 'get', 'getLast', 'add', 'getLast', 'remove', 'getLast'], [['a', 1], ['b', 2], ['a'], [], ['a', 3], [], ['a'], []])

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

Example 2

Input: process_store_operations(['getLast', 'add', 'getLast', 'remove', 'getLast'], [[], ['x', -4], [], ['x'], []])

Output: [None, None, -4, None, None]

Hints

Hint 1

Combining a standard hash table with a doubly linked list allows O(1) lookup as well as O(1) updates to insertion/modification order.

Hint 2

When a key is added or updated, unlink its node if it already exists in the linked list, then append it to the tail (representing the most recent item).

Hint 3

On removal, remove the key from the hash table and unlink its node from the linked list. The new tail automatically becomes the last active element.