LRU Cache
Updated
Problem statement
Design a least recently used (LRU) cache that holds at most capacity keys, and run a list of calls on it.
get(key): return the value stored forkey, or-1ifkeyis not in the cache.put(key, value): storevalueforkey. Ifkeyis already in the cache, replace its value. Ifkeyis new and the cache already holdscapacitykeys, first remove the least recently used key.
A key counts as used when a put stores it or a get finds it. A get for a missing key changes nothing.
The calls come as two lists of the same length. operations[i] is "get" or "put", and args[i] holds its arguments: [key] for a get and [key, value] for a put. Return the results of the get calls, in order.
Aim for O(1) average time for each get and put.
Function
lruCache(capacity: int, operations: String[], args: int[][]) → int[]Examples
Example 1
capacity = 2operations = ["put","put","get","put","get","get","get"]args = [[1,10],[2,20],[1],[3,30],[2],[3],[1]]return = [10,-1,30,10]The cache holds keys 1 and 2. get(1) returns 10 and makes key 1 the most recently used, so put(3, 30) removes key 2. Then get(2) returns -1, and keys 3 and 1 are still there.
Example 2
capacity = 2operations = ["put","put","put","put","get","get","get"]args = [[4,1],[7,2],[4,5],[9,3],[7],[4],[9]]return = [-1,5,3]put(4, 5) changes the value of key 4 and makes it the most recently used. When key 9 comes in, the least recently used key is 7, so key 7 is removed.
Example 3
capacity = 1operations = ["get","put","get","put","get","get"]args = [[5],[5,0],[5],[6,8],[5],[6]]return = [-1,0,-1,8]The first get(5) finds nothing and returns -1. Key 5 is then stored with value 0. With capacity 1, put(6, 8) removes key 5.
Constraints
1 <= capacity <= 30001 <= operations.length <= 3 * 10^4args.length == operations.length- Each
operations[i]is"get"or"put". For a get,args[i] = [key]. For a put,args[i] = [key, value]. 0 <= key <= 10^4and0 <= value <= 10^5- At least one call is a get.
More TypeSafe AI interview questions
Similar questions at other companies
- Least Recently Used CacheMicrosoft · OA · PHONE SCREEN · ONSITE INTERVIEWMicrosoft interview questions
- LFU CacheSnowflake · OA · ONSITE INTERVIEWSnowflake interview questions
- LFU CacheArista Networks · OAArista Networks interview questions
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- LRU CacheServiceNow · PHONE SCREEN · ONSITE INTERVIEWServiceNow interview questions
- LRU CacheLotusFlare · ONSITE INTERVIEW
- LRU CacheGimlet Labs · PHONE SCREEN
- LRU CacheBNSF Railway · PHONE SCREENBNSF Railway interview questions
- LRU CacheJP Morgan Chase · ONSITE INTERVIEWJP Morgan Chase interview questions
- LRU Cache OperationsHevo Data · ONSITE INTERVIEW