KatInterview

Replay a Recency-Evicting Cache from a Command Log

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designlru-cachehash-mapordered-dict

Last updated

Simulate a fixed-size cache that evicts the least recently used entry, by replaying text commands and collecting the answers to lookups in order.

Replay a Recency-Evicting Cache from a Command Log

A small cache stores integer keys mapped to integer values. It can hold at most capacity entries. When it overflows, it discards the entry that was used least recently.

You are given the cache size and a list of text commands. Replay the commands in order and report what each lookup returns.

Commands

Each command is a string in one of these two forms:

  • "PUT key value" stores value under key.
    • If key is already present, its value is overwritten and it becomes the most recently used entry. No new entry is created.
    • If key is new, it is added as the most recently used entry. If the cache now holds more than capacity entries, the least recently used entry is removed.
  • "GET key" looks up key.
    • If present, record its value and mark the key as the most recently used.
    • If absent, record -1. A missing key changes nothing, including recency order.

An entry is "used" whenever it is written by a PUT or successfully read by a GET.

Task

Implement process_lru(capacity, operations). Return a list containing the recorded result of every GET command, in the order the GETs appear. If there are no GET commands, return an empty list.

Note that a stored value of -1 looks identical to a miss in the output. Do not treat this specially.

Constraints

  • 1 <= capacity <= 100000
  • 0 <= len(operations) <= 200000
  • Keys and values are integers in the range [-10^9, 10^9] (they may be negative).
  • Every command matches one of the two formats above, with single spaces between tokens.

Examples

Example 1

Input: process_lru(2, ['PUT 1 10', 'PUT 2 20', 'GET 1', 'PUT 3 30', 'GET 2', 'GET 3'])

Output: [10, -1, 30]

Example 2

Input: process_lru(1, ['PUT 7 4', 'PUT 7 9', 'GET 7', 'PUT 8 5', 'GET 7', 'GET 8'])

Output: [9, -1, 5]

Hints

Hint 1

Two things must be fast: finding a key, and finding which key was used longest ago. Think about what structure gives you both.

Hint 2

Keep the keys in an ordering from least to most recently used. Each PUT and each successful GET moves its key to the recent end; eviction removes from the old end.

Hint 3

Python's OrderedDict supports moving a key to the end and popping from the front in O(1). Remember to evict only after inserting, and only when size exceeds capacity; also make sure a miss changes nothing.