You’re building a real-time patient monitoring UI for a large hospital network. The backend emits vitals readings (heart rate, SpO₂, respiratory rate, etc.) from bedside devices. Due to Wi‑Fi jitter and device batching, events can arrive out of timestamp order, but the system guarantees a bounded lateness: an event’s timestamp will never be more than L seconds behind the maximum timestamp seen so far.
Rendering every raw event causes flicker and wasted work. The UI wants a clean stream of updates:
(timestamp, metric), only the last arriving value should be emitted (last-write-wins).Implement coalesce_vitals(events, L).
events: list[tuple[int, str, int]] where each event is (t, metric, value)L: non-negative integer lateness bound(t, metric, value) in the required order.Let max_seen_t be the maximum timestamp observed so far while scanning events in arrival order. After processing each event, you must flush (emit) all buffered timestamps t such that:
t <= max_seen_t - LAt end of stream, flush everything remaining.
Example 1
events = [(100,"HR",80), (90,"HR",78), (95,"SpO2",97), (100,"HR",81)], L = 5[(90,"HR",78), (95,"SpO2",97), (100,"HR",81)]max_seen_t=100, cutoff is 95, so timestamps <=95 flush. At t=100, HR is overwritten to 81 before the final flush.Example 2
events = [(5,"HR",70), (5,"HR",71), (5,"SpO2",98), (5,"SpO2",97)], L = 0[(5,"HR",71), (5,"SpO2",97)]L=0, timestamp 5 is immediately flushable, but within that timestamp we still apply last-write-wins per metric.1 <= events.length <= 2 * 10^50 <= t <= 10^90 <= L <= 10^91 <= metric.length <= 10 (letters/digits/underscore)-10^6 <= value <= 10^6(t, metric) may appear; only the last one (by arrival order) should be emitted."HR" < "SpO2").