progress

~/problems / Streams & durability / Fault-tolerant work queue

Expire leases with a min-heap

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A worker that claims a task gets a lease until a deadline. If it doesn't finish or renew in time, the queue must notice. This drill is that bookkeeping.

Build Leases with:

  • grant(task_id, deadline): lease the task until deadline. Granting again replaces the deadline (a heartbeat; it may move earlier).
  • release(task_id): the task is done and has no lease. Unknown tasks: do nothing.
  • expired(now) -> list[str]: remove and return every leased task with deadline <= now, by deadline, ties by task id.
L = Leases()
L.grant("a", 10)
L.grant("b", 5)
L.grant("c", 5)
L.grant("a", 20)     # heartbeat: a now expires at 20
L.release("c")       # c is done
L.expired(9)         # ["b"]
L.expired(9)         # []   (b was already returned)
L.expired(25)        # ["a"]

⭐ Bonus: scanning every lease in expired still passes; a speed test with many leases earns a star if expired only touches what it returns (O(log n) each).

Show hint

push (deadline, task_id) onto a heapq and keep a dict of current deadlines; skip popped entries that don't match it (lazy deletion).

Topic: Fault-tolerant work queue. Leases with deadlines in a min-heap; explicit task states.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc