Code RoomTTL cache
MediumPrep Room Coding #1524

TTL cache

CodingStorage & CDNMid–Senior~25 min

Implement a TTL cache. Process operations of three shapes: ["set", now, key, value, ttl] stores key=value at time `now` with a time-to-live of `ttl` (the entry expires at now+ttl, i.e. it is alive for times strictly less than now+ttl), ["get", now, key] returns the value if the key exists and now < its expiry, else -1, and ["count", now] returns how many keys are currently alive at time `now`. Setting an existing key overwrites its value and resets its expiry. Timestamps are non-decreasing non-negative integers. Return the list of results from every get and count operation, in order.

Implement
ttl_cache(ops: list[list]) → list[int]
Examples
in[[["set",0,"a",10,5],["count",2],["get",2,"a"],["get",5,"a"]]]out[1,10,-1]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 25 min
InputExpectedGot
[[["set",0,"a",10,5],["count",2],["get",2,"a"],["get",5,"a"]]][1,10,-1]not run yetsample