KatInterview

Recency-Evicting Cache Simulator

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designhash-mapdoubly-linked-listlru-cache

Last updated

Simulate a fixed-capacity key-value store that evicts the least recently used entry, processing a batch of get and put commands in constant time each.

Recency-Evicting Cache Simulator

You are given the size limit of a small key-value store and a list of commands to run against it, in order. The store keeps at most capacity entries. When it is full and a brand-new key arrives, it throws away the entry that was used least recently.

Return the result of every command.

Commands

Command i is commands[i], and its arguments are params[i].

  • "get" with params[i] = [key]: if key is in the store, the result is its value. Otherwise the result is -1. A successful lookup makes that key the most recently used one. A failed lookup changes nothing.
  • "put" with params[i] = [key, value]: the result is None.
    • If key is already stored, replace its value and mark it as the most recently used. No entry is evicted, since the number of entries does not change.
    • If key is new, insert it as the most recently used entry. If the store then holds more than capacity entries, remove the least recently used one.

The store starts empty. Only successful get calls and put calls (both inserts and updates) count as "using" a key.

Output

Return a list with one element per command, in the same order: the retrieved value or -1 for each get, and None for each put.

Performance goal

Each command should take O(1) time on average, so the whole batch runs in time linear in the number of commands.

Constraints

  • capacity is a positive integer.
  • commands and params have the same length, at most 10^5.
  • Each command is either "get" or "put", with the argument list matching its form above.
  • Keys and values are integers.
  • Capacity 1 is valid, and get on a missing key is valid.

Examples

Example 1

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

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

Example 2

Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'get', 'put', 'get'], [[1, 10], [2, 20], [1], [1, 15], [2], [1], [3, 30], [3]])

Output: [None, None, 10, None, 20, 15, None, 30]

Hints

Hint 1

Two things are needed at once: finding a key instantly, and knowing which key was touched longest ago. Think about which structure gives each.

Hint 2

A hash map alone cannot cheaply move an entry to the 'newest' position. A doubly linked list lets you unlink a node you already hold in O(1), so have the map point directly at list nodes.

Hint 3

Check whether the key already exists before deciding to evict. Updating an existing key in a full store must never remove anything. Also store the key inside each node so you can delete the map entry when you evict.