2Brute2Best
πŸ”₯0

LRU Cache

MediumΒ·LeetCode #146 Pro OnlyMedium
LeetCode
01

Problem Statement

Build a class LRUCache: a key–value store with a fixed size limit. When it is full and a new key arrives, it throws out the key that was used longest ago (the least recently used, "LRU").

  • LRUCache(int capacity) creates an empty cache that can hold at most capacity keys.
  • int get(int key) returns the value of key, or -1 if it is not stored. A successful get counts as a use of that key.
  • void put(int key, int value) stores value under key. If the key already exists, its value is replaced. Otherwise it is added, and if that makes the cache hold more than capacity keys, the least recently used key is removed first. A put also counts as a use.

Both get and put must run in O(1) average time.

Input

The capacity, then a sequence of get(key) and put(key, value) calls.

Output

For each get, the stored value or -1. put returns nothing.

Example 1
Input: capacity = 2 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 (the results of the five get calls)

After get(1), key 1 is the most recent, so put(3, 3) evicts key 2. Then key 1 is the oldest, so put(4, 4) evicts key 1. Keys 3 and 4 remain.

Constraints
  • β€’ 1 ≀ capacity ≀ 3000
  • β€’ 0 ≀ key ≀ 10^4
  • β€’ 0 ≀ value ≀ 10^5
  • β€’ At most 2 Β· 10^5 calls to get and put
02

Pattern Recognition Clues

Recognising these key signals in the problem description immediately identifies the pattern:

β€œget and put in O(1)”
β†’ No scanning β†’ a hash map to find keys.
β€œleast recently used”
β†’ We need an order of use, with the oldest easy to remove β†’ a list with an old end.
β€œa use moves the key to the front”
β†’ Items must jump from the middle to the front β†’ a doubly linked list, not a queue or vector.
03

Approach Complexity Ladder

Brute Force β€” vector in recency orderO(C)O(C)

Vector of (key, value) from most to least recent; linear search on every call

Optimal β€” hash map + doubly linked listO(1)O(C)

List keeps recency order; map key β†’ list node; splice to front, evict from back

Brute Force Intuition

Keep a vector<pair<int,int>> ordered from most recently used (index 0) to least recently used (the back). get and put search the vector for the key. On a hit, erase the pair and re-insert it at the front. To evict, pop_back.

Recognition rule for this sub-pattern:

You must support operations in O(1); combine a hash map with another structure (list, array) so each one covers the other's weakness.
Remember this Β· Arrays & Hashing
Trigger
"Have I seen X before?", pairs that add up to a target, grouping things that look alike, counting occurrences.
Think
Instead of scanning again for each element, can I remember earlier elements in a map?
Key question
What exactly do I store as the key, and what as the value?
Brute2Best Pro Content

Unlock Complete Visual Walkthrough & Optimal C++

The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.