v9.1.1
Menu

LRU Cache

mediumFREEDesign & Hash MapsUber DSA

Design a data structure for a Least Recently Used (LRU) cache. Support get(key) and put(key, value) in O(1) time. When capacity is exceeded, evict the least recently used item.

Input: operations as op,args separated by semicolons. Output results of get operations (-1 if not found).

Example

Input
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
Reasoning
  • The cache is initialized with a capacity of 22, so it can hold up to 22 key-value pairs.
  • The input operations are executed in sequence: put(1,1), put(2,2), get(1) returns 11, put(3,3) evicts 2 due to LRU, get(2) returns −1-1 as 22 is no longer in the cache.
  • Continuing with the sequence: put(4,4) evicts 1, get(1) returns −1-1, get(3) returns 33, and get(4) returns 44.
  • The output is generated by the get operations, resulting in 11, −1-1, −1-1, 33, 44.

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key, value <= 10^4

Learn this in

More from Uber DSA

solution.py

Test results

Sign in to run your code against the test cases.