Rolling Forklift Ping Counts with Late Arrivals and Shift Tracking
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a fleet telemetry service that tracks per-forklift pings in a global 15-minute window, handles late pings, and counts clocked-in forklifts.
You are given a sequence of operations on a forklift telemetry system. Process them in order and return one result per operation.
Each forklift is identified by the pair (depot, forklift), where depot is a string and forklift is an integer that is unique only within its depot. The operations are:
"ping"with arguments[depot, forklift, ts]: records a ping from that forklift at minutets(an integer). ReturnsNone."count_recent"with arguments[depot, forklift]: returns how many pings from that forklift are currently inside the window. Returns an integer."clock_in"with arguments[depot, forklift]: marks that forklift as on shift. Clocking in an already-active forklift changes nothing. ReturnsNone."clock_out"with arguments[depot, forklift]: removes that forklift from the on-shift set. Clocking out a forklift that is not on shift does nothing. ReturnsNone."active_shift_count"with arguments[]: returns how many distinct forklifts are currently on shift. Returns an integer.
The window. Let T be the largest ts seen so far in any ping operation, across all depots and forklifts. Before any ping has been processed, T is undefined and every count_recent returns 0. Once T exists, the window is the closed interval [T - 14, T]. A ping counts toward the window if and only if its ts lies in that interval. For example, with T = 40 the window is [26, 40], so a ping at minute 26 counts and a ping at minute 25 does not.
Key rules:
Tis global. A ping from one forklift can advance the window and cause other forklifts' old pings to fall out of it.- Pings may arrive out of order. A ping whose
tsis earlier thanTis still recorded iftsis inside the current window. A ping whosetsis already beforeT - 14is outside the window and contributes nothing to any count. - Duplicate timestamps are allowed. Each ping counts separately, even if it has the same forklift and the same minute as another ping.
- Shift state does not depend on the window or on pings.
Output: return a list with one entry per operation, in the same order. Use None for ping, clock_in, and clock_out. Use an integer for count_recent and active_shift_count.
Constraints
1 <= len(operations) == len(arguments) <= 2 * 10^5- Each operation is one of
"ping","count_recent","clock_in","clock_out","active_shift_count". depotis a non-empty string;forkliftis an integer.tsis an integer.- Argument lists match the operation as described above.
- Memory use should depend on the pings currently inside the window, not on the full history of the stream.
Examples
Example 1
Input: telemetry_session(['ping', 'ping', 'ping', 'ping', 'count_recent', 'count_recent'], [['D1', 1, 1], ['D1', 1, 3], ['D1', 2, 5], ['D1', 1, 20], ['D1', 1], ['D1', 2]])
Output: [None, None, None, None, 1, 0]
Example 2
Input: telemetry_session(['clock_in', 'clock_in', 'active_shift_count', 'clock_out', 'active_shift_count'], [['D1', 1], ['D1', 1], [], ['D1', 1], []])
Output: [None, None, 1, None, 0]
Hints
Hint 1
Track the global maximum `T` as pings arrive. A ping older than `T - 14` can be discarded immediately, since it will never fall inside the window again.
Hint 2
Store the live pings in a min-heap ordered by timestamp, alongside a per-forklift count. When `T` advances, pop every heap entry with `ts < T - 14` and decrement that forklift's count, removing the forklift when its count reaches zero.
Hint 3
Shift tracking is independent of the window: use a plain set for clock-in and clock-out, and return its size for `active_shift_count`.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep three pieces of state: the newest timestamp newest seen so far, a dictionary counts mapping each (depot, forklift) to how many of its pings are still in the window, and a min-heap of every live ping keyed by its timestamp.
For a ping:
- If
tsis larger thannewest, advancenewest. The new window floor isnewest - 14. Pop heap entries while their timestamp is below that floor, and decrement the matching forklift count. Delete the dictionary entry when the count hits zero. - After advancing, record the new ping only if
ts >= newest - 14. Late pings that are already outside the window are ignored, because they could never contribute to a count.
Heap entries are (ts, seq, key). The sequence number breaks ties so that tuples with equal timestamps never compare the key objects.
count_recent reads the forklift's count from the dictionary, defaulting to 0. Clock-in, clock-out, and the active-shift count use a plain set and are independent of the window.
Why it is correct
The heap always yields the smallest live timestamp first. Whenever the window moves forward, every ping below the new floor is at the top of the heap in order, so popping while ts < floor removes exactly the pings that have left the window and nothing else. A ping that arrives late is only admitted when it lies within the current window, so the counts always equal the number of live pings inside [T-14, T] for each forklift. Expired pings are removed only when the window advances, and between advances nothing leaves the window, so the counts are never stale when queried.
Complexity
ping: amortized O(log m), where m is the number of pings currently in the window. Each ping is pushed once and popped at most once.count_recent: O(1).clock_in,clock_out,active_shift_count: O(1) each.- Memory: O(m) for pings inside the window, plus O(f) for forklifts with active pings and O(s) for clocked-in forklifts.
Reference solution
import heapq
from typing import List, Optional
def telemetry_session(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
newest = None
counts = {}
heap = []
seq = 0
shifts = set()
out: List[Optional[int]] = []
for op, args in zip(operations, arguments):
if op == "ping":
depot, forklift, ts = args
key = (depot, forklift)
if newest is None or ts > newest:
newest = ts
floor = newest - 14
while heap and heap[0][0] < floor:
_, _, expired = heapq.heappop(heap)
left = counts[expired] - 1
if left:
counts[expired] = left
else:
del counts[expired]
if ts >= newest - 14:
counts[key] = counts.get(key, 0) + 1
heapq.heappush(heap, (ts, seq, key))
seq += 1
out.append(None)
elif op == "count_recent":
depot, forklift = args
out.append(counts.get((depot, forklift), 0))
elif op == "clock_in":
depot, forklift = args
shifts.add((depot, forklift))
out.append(None)
elif op == "clock_out":
depot, forklift = args
shifts.discard((depot, forklift))
out.append(None)
elif op == "active_shift_count":
out.append(len(shifts))
else:
raise ValueError("unknown operation")
return out