---
title: LRU cache simulator
url: https://gurkanozkan.ai/learn/coding/mle-lru-cache-simulator-31/
markdown: https://gurkanozkan.ai/learn/coding/mle-lru-cache-simulator-31.md
kind: coding
difficulty: Easy
topics:
  - Design
  - Hash map
  - Linked list
json: https://gurkanozkan.ai/api/learn/coding/mle-lru-cache-simulator-31.json
robots: noindex
---

# LRU cache simulator

Simulate an LRU cache with the given capacity. Operations are `("put", key, value)` or `("get", key)`: - `get` returns the value (or −1 if absent) and marks the key as most recently used. - `put` inserts or updates the key and marks it most recently used. When the size exceeds capacity, evict the least recently used key. Return the list of `get` results. Each operation must be O(1).

## Signature

```python
def lru_simulate(capacity: int, ops: list[tuple]) -> list: ...
```

## Examples

Each call and the value it should give.

```python
>>> lru_simulate(2, [('put',1,1),('put',2,2),('get',1),('put',3,3),('get',2),('get',3),('get',1)]) == [1, -1, 3, 1]
True

>>> lru_simulate(1, [('put','a',1),('put','b',2),('get','a'),('get','b')]) == [-1, 2]
True
```

## Hints

1. Hash map plus a doubly linked list (or OrderedDict move_to_end / popitem(last=False)).
2. get marks the key most recently used; put inserts/updates and refreshes recency; evict the least-recently-used on overflow.
3. Each operation is O(1).

## Reference solution

```python
from collections import OrderedDict

def lru_simulate(capacity, ops):
    from collections import OrderedDict
    c = OrderedDict(); out = []
    for op in ops:
        if op[0] == "get":
            k = op[1]
            if k in c:
                c.move_to_end(k); out.append(c[k])
            else:
                out.append(-1)
        else:
            _, k, v = op
            if k in c:
                c.move_to_end(k)
            c[k] = v
            if len(c) > capacity:
                c.popitem(last=False)
    return out
```

## What a strong solution covers

- Hash map plus a doubly linked list (or `OrderedDict.move_to_end` / `popitem(last=False)`).
- Updates refresh recency.
- Discusses thread safety and TTL, and its use as a feature/embedding cache in serving.

## Common mistakes

- forgetting to refresh recency on `get` or on updating `put`
- O(n) eviction by scanning.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
