Hash map · Medium
A service cache evicts the least recently used key when capacity is exceeded. Reads and overwrites both update recency.
Simulate get and put operations and return get results.
Input
Call
- Implement
solve(input)and return its result. Do not print fromsolve.
Input object
{ capacity:integer, operations:({type:"get",key:string}|{type:"put",key:string,value:integer})[] }
What each field means
capacity— maximum number of keys the cache can hold.operations— orderedgetandputactions. Aputincludes an integervalue.
Output
Return value and rules
- Return one value per
get, ornullwhen its key is absent. - A successful read or a write makes that key most recently used.
- If a new key exceeds capacity, evict the least recently used key. Capacity zero stores nothing.
putoperations do not add result elements.
Constraints
- 0 <= capacity <= 100000; at most 100000 operations
- Keys are ASCII strings up to 40 characters; values in [-1000000,1000000]. Missing keys return null.
Examples
Example 1
{
"capacity": 2,
"operations": [
{
"type": "put",
"key": "a",
"value": 1
},
{
"type": "put",
"key": "b",
"value": 2
},
{
"type": "get",
"key": "a"
},
{
"type": "put",
"key": "c",
"value": 3
},
{
"type": "get",
"key": "b"
}
]
}Returns
[
1,
null
]Example 2
{
"capacity": 0,
"operations": [
{
"type": "put",
"key": "a",
"value": 1
},
{
"type": "get",
"key": "a"
}
]
}Returns
[
null
]Required complexity
O(q) expected time and O(capacity) space