KatInterview

Simulate a Bounded Recency-Evicting Key-Value Store

Data Structure DesignAuto-graded · 16 test cases
MediumAuto-gradedData Structure Designlru-cachehash-maplinked-list

Last updated

Replay a batch of get/put commands against a fixed-capacity store that discards its least recently used key on overflow, with O(1) average cost per command.

Bounded Recency Store

A key-value store holds at most capacity entries. Keys and values are integers. When the store grows beyond its capacity, it throws away the entry that was used least recently.

You are given the capacity and a list of commands to run against an initially empty store, in order. Return the result of every command.

Commands

  • "get" with arguments [key]: if key is in the store, return its value and mark key as the most recently used. Otherwise return -1 and leave the store unchanged.
  • "put" with arguments [key, value]: set the value for key, inserting it if it is absent or overwriting it if it exists. In both cases key becomes the most recently used. If the number of entries now exceeds capacity, remove the least recently used entry. A put always produces None as its result.

"Used" means any get that finds the key, or any put on the key. A get on a missing key does not affect recency.

The check for overflow happens after the insertion or update. Overwriting an existing key never increases the size, so it never causes an eviction.

Input

  • capacity: a positive integer.
  • operations: a list of strings, each either "get" or "put".
  • arguments: a list of the same length as operations. arguments[i] is the argument list for operations[i]: [key] for a get, [key, value] for a put.

Output

A list with one entry per command, in order: the retrieved value (or -1) for each get, and None for each put.

Constraints

  • capacity >= 1
  • len(operations) == len(arguments)
  • Keys and values are integers.
  • Each command should run in O(1) average time.

Examples

Example 1

Input: run_recency_store(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])

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

Hints

Hint 1

You need to find a key quickly and also keep track of which key has gone unused the longest. A hash map alone handles the first need but not the second.

Hint 2

Pair a hash map with an ordering of keys from least to most recently used, such as a doubly linked list. Moving a known node to the 'most recent' end must be O(1).

Hint 3

In Python, collections.OrderedDict gives you move_to_end and popitem(last=False). Remember to refresh recency on a put for an existing key, and to evict only after inserting.