Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-195

TTL Cache Purge Logic

Problem

Simulate a cache whose entries expire after a time-to-live and can be purged explicitly.

ttl is the maximum idle time. operations contains "set" (keys[i], values[i] at times[i]), "get" (lazily removes the key when it has expired and returns its value or -1), "purge" (removes all expired entries and records how many were removed), or "size" (record the number of live entries). An entry expires when times[i] - stored_time is at least ttl.

Return the list of recorded results (None for set).

Hint

A get refreshes nothing: expiry is measured from the last set for that key.

Test cases

case 1
in: [5,["set","set","get","purge","size","get"],[1,2,1,0,0,2],[10,20,0,0,0,0],[0,0,3,5,5,5]]
expected: [null,null,10,2,0,-1]
case 2
in: [10,["set","purge","size"],[1,0,0],[5,0,0],[0,9,9]]
expected: [null,0,1]
case 3
in: [3,["get"],[1],[0],[10]]
expected: [-1]
case 4
in: [3,["set","get","size"],[1,1,0],[7,0,0],[0,2,2]]
expected: [null,7,1]
Starter codePython
def ttl_purge_cache(ttl, operations, keys, values, times):
    # Your code here
    pass

4 test cases · run your code against them in the editor