← All Exercises

LRU Cache with OrderedDict

intermediatepython~25min

Background

LRU caches keep the working set small by discarding the entry that has gone unused the longest; a hash map plus a doubly linked list gives O(1) operations.

Problem

Implement an LRUCache class with a positive capacity. get(key) returns the stored value or -1 and marks the key as most recently used; put(key, value) inserts or updates and evicts the least recently used key when capacity is exceeded.

Input

A sequence of operations against a cache constructed with a fixed capacity.

Output

The list of values returned by get calls, using -1 for misses.

Sample tests

Sample 1

Input: capacity = 1; put(1, 1), get(1), put(2, 2), get(1), get(2)
Expected: [1, -1, 2]

Sample 2

Input: capacity = 2; put(1, 1), put(2, 2), get(1), put(3, 3), get(2), get(3), get(1)
Expected: [1, -1, 3, 1]

Your solution

Learning objective

Use OrderedDict to build an O(1) LRU cache and understand recency updates on both get and put.