Hash map · Hard
A service uses a bounded cache and records its get and put operations. You are building a deterministic replay tool that predicts every get result under least-recently-used eviction. There is no clock, expiry or external storage in this exercise.
Process the operations in order and return each get result while enforcing cache capacity and recency on reads and writes.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "capacity": number, "operations": { "type": "get"|"put", "key": string, "value"?: number }[] }.
Fields
- capacity is a non-negative integer.
- Each operation is {type:"get",key} or {type:"put",key,value}. Keys are case-sensitive ASCII strings; values are signed integers.
Output
Return value
- Return an array containing only get results, in operation order. A miss returns -1.
- A successful get makes its key most recently used; a miss does not change recency.
- A put inserts or replaces its key and makes it most recently used, including a same-value replacement.
- After a new insertion exceeds capacity, evict the least recently used key.
- Capacity zero stores nothing. An actual stored -1 is still a hit and must update recency.
Constraints
- 0 <= capacity <= 100000 and 0 <= operations.length <= 100000.
- Key length is 0..40 ASCII characters; empty keys and proto are valid.
- Values are integers in [-1000000000,1000000000].
- Use expected O(1) work per operation; rescanning or sorting all cached keys is not acceptable. Ordered maps with constant-time refresh/eviction are allowed.
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"
},
{
"type": "get",
"key": "c"
}
]
}Returns
[
1,
-1,
3
]Reading a refreshes it, so inserting c evicts b.
Example 2
{
"capacity": 0,
"operations": [
{
"type": "put",
"key": "a",
"value": 1
},
{
"type": "get",
"key": "a"
}
]
}Returns
[
-1
]A zero-capacity cache never keeps a value.
Required complexity
O(q) expected total time and O(capacity) cache space, excluding input and output