Practice Problem

LRU Cache

Difficulty: Medium

Design a data structure that follows the Least Recently Used (LRU) cache constraints, supporting get and put operations in O(1) time.

LRU Cache

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

Implement the LRUCache class:

  • LRUCache(capacity): Initialize the LRU cache with a positive size capacity.
  • get(key): Return the value of the key if the key exists, otherwise return -1.
  • put(key, 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, evict the least recently used key.

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

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);
cache.put(1, 1);    // cache is {1=1}
cache.put(2, 2);    // cache is {1=1, 2=2}
cache.get(1);       // return 1
cache.put(3, 3);    // evicts key 2, cache is {1=1, 3=3}
cache.get(2);       // return -1 (not found)
cache.put(4, 4);    // evicts key 1, cache is {4=4, 3=3}
cache.get(1);       // return -1 (not found)
cache.get(3);       // return 3
cache.get(4);       // return 4

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • At most 2 * 10^5 calls will be made to get and put.

Expected Complexity

  • Time: O(1) for both get and put
  • Space: O(capacity)
MEDIUM
Singly Linked List
Doubly Linked List
Hash Map / Dictionary
LRU Cache
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium