LRU Cache
Updated
Problem statement
A least recently used (LRU) cache holds at most capacity keys, each with a value. Start with an empty cache and run the list operations on it, in order. Each operation is one of these:
GET key: ifkeyis in the cache, return its value, andkeybecomes the most recently used key. Otherwise return-1; the cache does not change.PUT key value: ifkeyis in the cache, change its value tovalue. Otherwise addkeywithvalue, but if the cache already holdscapacitykeys, first remove the least recently used key. Either way,keybecomes the most recently used key.
Return the results of the GET operations, in order.
Each GET and PUT should take O(1) average time.
Function
runLRU(capacity: int, operations: String[]) → int[]Examples
Example 1
capacity = 2operations = ["PUT 1 1","PUT 2 2","GET 1","PUT 3 3","GET 2","PUT 4 4","GET 1","GET 3","GET 4"]return = [1,-1,-1,3,4]GET 1 returns 1 and makes key 1 the most recently used, so PUT 3 3 removes key 2 and GET 2 returns -1. Then PUT 4 4 removes key 1, which was used less recently than key 3. The last three operations return -1, 3 and 4.
Example 2
capacity = 2operations = ["PUT 1 10","PUT 2 20","PUT 1 15","PUT 3 30","GET 1","GET 2","GET 3"]return = [15,-1,30]PUT 1 15 only changes the value of key 1, so the cache still holds 2 keys and nothing is removed. Key 1 is now the most recently used, so PUT 3 30 removes key 2.
Example 3
capacity = 1operations = ["GET 7","PUT 7 0","GET 7","PUT 8 5","GET 7","GET 8"]return = [-1,0,-1,5]The first GET 7 finds an empty cache, returns -1 and adds nothing. Then key 7 holds the value 0, which the next GET 7 returns. The cache has room for one key, so PUT 8 5 removes key 7.
Constraints
1 <= capacity <= 30001 <= operations.length <= 10^4- Each
operations[i]is eitherGET keyorPUT key value, with the parts separated by single spaces and the numbers written in decimal without leading zeros. 0 <= key <= 10^4and0 <= value <= 10^5
More Athenahealth interview questions
Similar questions at other companies
- LRU CacheApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- LRU Cache for Query ResultsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- LRU CacheServiceNow · PHONE SCREEN · ONSITE INTERVIEWServiceNow interview questions
- LRU Key-Value Cache OperationsCohesity · PHONE SCREEN
- Least Recently Used CacheMicrosoft · OA · PHONE SCREEN · ONSITE INTERVIEWMicrosoft interview questions
- Least Recently Used CacheByteDance · PHONE SCREEN · ONSITE INTERVIEWByteDance interview questions
- LRU CacheCoupang · PHONE SCREEN
- LRU CacheBlinkit · PHONE SCREENBlinkit interview questions
- LRU Cache with Thread-Safety Follow-UpSnap Inc. · PHONE SCREENSnap Inc. interview questions
- Least Recently Used CacheIllumio · PHONE SCREENIllumio interview questions