LRU cache with time-to-live

A free medium coding practice problem from databases. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Medium
Type
Function
Topic
Databases
Languages
JavaScript, TypeScript or Python

Problem

Simulate a cache holding at most capacity entries (≥ 1). ops is a list in non-decreasing time order of ["put", t, key, value, ttl] and ["get", t, key] (values are integers ≥ 0, ttl ≥ 1). An entry put at time t with ttl expires at t + ttl. Before EVERY operation at time t, remove all entries whose expiry is ≤ t. Then: a get returns the key's value (and makes it the most recently used) or -1 if absent; a put of an existing key replaces its value and expiry and makes it most recently used; a put of a new key into a full cache first evicts the least recently used entry. Return the results of the gets, in order.

Function signature

// JavaScript
function lruTtlCache(capacity, ops)

// TypeScript
function lruTtlCache(capacity: any, ops: any): any

// Python
def lru_ttl_cache(capacity, ops):

Examples

  1. lruTtlCache(2, [["put",0,"a",1,10],["put",1,"b",2,10],["get",2,"a"],["put",3,"c",3,10],["get",4,"b"],["get",4,"a"]]) → [1,-1,1]
  2. lruTtlCache(2, [["put",0,"a",1,5],["put",0,"b",2,100],["get",5,"a"],["put",6,"c",3,1],["get",6,"b"],["get",7,"c"]]) → [-1,2,-1]

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps