Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(int capacity) - Initialize the LRU cache with positive size capacity
  • int get(int key) - Return the value of the key if the key exists, otherwise return -1
  • void put(int key, int value) - Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.

The functions get and put must each run in O(1) average time complexity.

Input & Output

Example 1 — Basic LRU Operations
$ Input: capacity = 2, operations = [["put",1,1],["put",2,2],["get",1],["put",3,3],["get",2],["put",4,4],["get",1],["get",3],["get",4]]
Output: [null,null,1,null,-1,null,-1,3,4]
💡 Note: Cache capacity is 2. put(1,1), put(2,2) fills cache. get(1) returns 1. put(3,3) evicts key 2. get(2) returns -1 (evicted). put(4,4) evicts key 1. get(1) returns -1, get(3) returns 3, get(4) returns 4.
Example 2 — Single Capacity
$ Input: capacity = 1, operations = [["put",2,1],["get",2],["put",3,2],["get",2],["get",3]]
Output: [null,1,null,-1,2]
💡 Note: With capacity 1, each put operation evicts the previous key. put(2,1), get(2) returns 1, put(3,2) evicts key 2, get(2) returns -1, get(3) returns 2.
Example 3 — Update Existing Key
$ Input: capacity = 2, operations = [["put",1,1],["put",2,2],["put",1,10],["get",1],["get",2]]
Output: [null,null,null,10,2]
💡 Note: put(1,1), put(2,2), then put(1,10) updates existing key 1 to value 10 and moves it to most recent. get(1) returns 10, get(2) returns 2.

Constraints

  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 104
  • 0 ≤ value ≤ 105
  • At most 2 × 104 calls will be made to get and put

Visualization

Tap to expand
LRU Cache: Least Recently Used Eviction PolicyCapacity: 2, Operations: put(1,1), put(2,2), get(1), put(3,3)Initial StateEmpty Cacheput(1,1), put(2,2)[1:1] → [2:2]LRU MRUget(1) → return 1[2:2] → [1:1]LRU MRUput(3,3) → evict LRU[1:1] → [3:3]MRU MRUFinal Result[null,null,1,null]Operation resultsKey Operations: O(1) get/put with automatic LRU eviction
Understanding the Visualization
1
Input
Cache capacity and sequence of get/put operations
2
Process
Track usage order and evict LRU items when capacity exceeded
3
Output
Results of get operations and successful put operations
Key Takeaway
🎯 Key Insight: Combine hash map for fast lookup with doubly linked list for efficient LRU ordering and eviction
Asked in
Google 85 Amazon 72 Microsoft 68 Facebook 61 Apple 45
982.0K Views
Very High Frequency
~35 min Avg. Time
15.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen