KatInterview

Access-Tracked Key-Value Store

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designhash-mapdesignsimulation

Last updated

Build a dictionary that counts how many times each key has been retrieved, testing hash map design and state management.

Implement a key-value store that tracks retrieval frequency. You will receive a sequence of operations to perform and must return the result of each operation in order.

Your store must support four operations:

  • put: Insert or update a key-value pair. When a key is first inserted, initialize its access count to 0. Updating an existing key's value does not reset its count.
  • get: Retrieve the value for a key. If the key exists, increment its access count by 1 and return the value. If the key does not exist, return None.
  • delete: Remove a key and its associated access count. Deleting a non-existent key has no effect.
  • get_read_count: Return the total number of successful get operations for a key. Return 0 if the key does not exist or has been deleted.

Write a function that takes two parallel lists: one containing operation names and one containing their arguments. Return a list of results, one per operation. Operations that modify state return None.

Constraints

  • 1 ≤ number of operations ≤ 10⁵
  • Keys and values can be any hashable type or any type, respectively
  • Keys are case-sensitive strings in test cases
  • Access counts never overflow standard integer limits
  • Each operation list corresponds exactly to one argument list entry

Examples

Example 1

Input: access_tracked_store(['put', 'get', 'get', 'get_read_count', 'delete', 'get'], [['a', 10], ['a'], ['a'], ['a'], ['a'], ['a']])

Output: [None, 10, 10, 2, None, None]

Hints

Hint 1

Use two separate dictionaries: one for values and one for access counts. Keep them synchronized on insert and delete.

Hint 2

When updating an existing key with put, preserve its access count—only newly created keys start at 0.

Hint 3

The get operation is a read-modify-write: check existence, increment the counter, then return the value.