Skip to content
Coding · Hard · Leader election · Target O(n log n) · Staff

Lease-based leader timeline

Replay heartbeats from competing candidates against a lease and report who led when, and the gaps with no leader.

Statement

Candidates compete for one lease by sending heartbeats. heartbeats is a list of (time, candidate) in no particular order. Write leader_timeline(heartbeats, lease, window) that returns who held the lease across window = (start, end), as a list of (start, end, leader) segments. The segments are in order, cover the window exactly, and have None as the leader where nobody holds the lease.

A heartbeat at time t from a candidate that does not hold the lease takes it if it is free, and holds it until t + lease. A heartbeat from the holder at any time up to and including the expiry renews it: the lease now runs until t + lease and the holder's segment carries on unbroken. A heartbeat from anyone else while the lease is held is ignored; it does not queue.

The lease is free to others from the expiry instant itself. So at that instant the holder renews if it sends a heartbeat then, and otherwise a rival that sends one takes over. When several candidates send a heartbeat at the same time, the holder is handled first; if the lease is then free, the candidate whose name sorts first takes it and the rest are ignored.

A holder whose heartbeat arrives after the expiry has lost the lease: there is a gap from the expiry to that heartbeat, which then competes for a new lease like any other. Heartbeats before the window still decide who holds the lease when the window opens. Heartbeats at or after its end change nothing.

Examples

lease = 10, window = (0, 60)

heartbeats = [(0, "a"), (5, "b"), (8, "a"), (18, "a"),
              (30, "b"), (31, "a"), (40, "b"), (52, "a")]
→ [(0, 28, "a"), (28, 30, None), (30, 50, "b"),
   (50, 52, None), (52, 60, "a")]

# a renews at 8 (until 18) and again at 18, exactly at expiry (until 28).
# b at 5 and a at 31 are ignored: the lease is held by someone else.
# a's last lease would run to 62; the window cuts it at 60.

Constraints

Up to 10⁵ heartbeats. Times and lease are numbers; lease is greater than 0, and times may be negative or fractional. The same heartbeat may appear more than once. An empty window (start ≥ end) has no segments.

Open to everyone until Pro goes on sale · sign in to save your attemptSolve it in the editor with visible tests
Open in the app