Design an LRU cache

A design question that interviews love: a cache with a fixed capacity that throws away the least recently used entry when it is full.

What to build

A program that simulates an LRU cache from a list of commands.

Requirements

  • put k v stores the value (updating it if the key exists) and makes the key the most recently used; if the cache is over capacity, remove the least recently used key.
  • get k prints the value, or -1 if the key is absent, and makes the key the most recently used.
  • Print one line for each get, in order.

Input

The first line has capacity and q. Each of the next q lines is put k v or get k (integers).

Output

One line per get.

Constraints

1 ≤ capacity ≤ 100; 1 ≤ q ≤ 10⁴.

Example

Input:

2 9
put 1 1
put 2 2
get 1
put 3 3
get 2
put 4 4
get 1
get 3
get 4

Output:

1
-1
-1
3
4

Why it works

An ordered dictionary keeps keys in order of use, so the least recently used key is always first. Moving a key to the end and removing from the front are both O(1), so every command is O(1).

Examples

Example 1 · Input
2 9
put 1 1
put 2 2
get 1
put 3 3
get 2
put 4 4
get 1
get 3
get 4
Expected output
1
-1
-1
3
4
Example 2 · Input
1 4
put 1 5
put 1 6
get 1
get 2
Expected output
6
-1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

OrderedDict from collections remembers the order of keys; move_to_end marks a key as most recent.

Hint 2

Both get and put make a key the most recently used. A put of an existing key only updates its value.

Hint 3

When the size goes above the capacity, remove the oldest key with popitem(last=False).

Solution

Show one correct solution (try it yourself first)
from collections import OrderedDict

capacity, q = map(int, input().split())
cache = OrderedDict()
for _ in range(q):
    parts = input().split()
    if parts[0] == "put":
        k, v = int(parts[1]), int(parts[2])
        cache[k] = v
        cache.move_to_end(k)
        if len(cache) > capacity:
            cache.popitem(last=False)
    else:
        k = int(parts[1])
        if k in cache:
            cache.move_to_end(k)
            print(cache[k])
        else:
            print(-1)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: The mock interview →