AlgoLounge

LRU Cache

hard

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 it exists, otherwise return -1.
  • void put(int key, int value) — Update the value of the key if it 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.

Example

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]

Constraints

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

How the tests work: each test is a sequence of calls. operations[i] is the method called with arguments[i]; the first entry constructs the class. The expected output lists what every call returns — null for the constructor and for methods that return nothing.

TypeScript
Loading editor…
List of test cases (4)
Case 1
operations = ["LRUCache","put","put","get","put","get","put","get","get","get"]
arguments = [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
Case 2
operations = ["LRUCache","put","get"]
arguments = [[1],[2,1],[2]]
Case 3
operations = ["LRUCache","put","put","put","get","get"]
arguments = [[2],[1,10],[2,20],[3,30],[1],[2]]
Case 4
operations = ["LRUCache","put","put","get","put","put","get"]
arguments = [[2],[1,1],[2,2],[1],[3,3],[4,4],[2]]