Asked at Marshall Wace
Theory: Algorithms Under a Complexity BoundRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in Python. Switch to C++
Given the time of every message a session sent, find the most messages that fall inside any one window of a fixed length.
The venue meters the session: no more than a fixed number of messages in any 60-second window, and a breach disconnects you mid-trade. The gateway logs the time of every message it sends, so the question after a busy day is how close the session came to the limit.
The log is a list of integer timestamps in seconds, already sorted in non-decreasing order (two messages in the same second share a timestamp). A window is a half-open interval \([t, t + w)\): a message at exactly \(t + w\) belongs to the next window, not this one. The window may start at any time, not only at a message.
Implement max_events_in_window(timestamps, window) returning the largest
number of timestamps that fall inside some window of length window. An
empty log returns 0.
def max_events_in_window(timestamps: list[int], window: int) -> int: ...
max_events_in_window([0, 10, 20, 70, 80], 60)
# 3 (the window [0, 60) holds 0, 10 and 20)
max_events_in_window([5, 5, 30, 64, 65, 100], 60)
# 4 (the window [5, 65) holds 5, 5, 30 and 64; 65 is outside it)
0 <= timestamps[i] <= 10^9,
sorted in non-decreasing order. Timestamps may repeat.window is a positive integer.