LRU Cache

medium · linked-list, hash-map, design

LRU Cache

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.

Interface

type LRUCache struct {
    // your fields here
}

func Constructor(capacity int) LRUCache
func (this *LRUCache) Get(key int) int
func (this *LRUCache) Put(key int, value int)

Examples

Example 1:

Input:
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]

Output:
[null, null, null, 1, null, -1, null, -1, 3, 4]

Explanation:
LRUCache cache = new LRUCache(2);  // capacity = 2
cache.put(1, 1);                   // cache: {1=1}
cache.put(2, 2);                   // cache: {1=1, 2=2}
cache.get(1);                      // returns 1, cache: {2=2, 1=1}
cache.put(3, 3);                   // evicts key 2, cache: {1=1, 3=3}
cache.get(2);                      // returns -1 (not found)
cache.put(4, 4);                   // evicts key 1, cache: {3=3, 4=4}
cache.get(1);                      // returns -1 (not found)
cache.get(3);                      // returns 3
cache.get(4);                      // returns 4

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10000
  • 0 <= value <= 100000
  • At most 200000 calls will be made to Get and Put

Hints

  1. Use a hash map for O(1) key lookup.
  2. Use a doubly linked list to maintain access order.
  3. Most recently used at head, least recently used at tail.
  4. When accessing a key, move its node to the head.

Notes

  • The key insight is combining O(1) hash lookup with O(1) list insertion/removal.
  • Doubly linked list allows O(1) removal of any node (if you have the pointer).
  • Use dummy head and tail nodes to simplify edge cases.
  • Store the key in the node so you can remove from hash map during eviction.
Run tests to see results
No issues detected