Find Peak Event Density in Fixed Duration Window
Greedy & IntervalsAuto-graded · 24 test casesLast updated
Determine the maximum number of recorded logs occurring within a contiguous time interval using a sliding window approach.
Given a list of non-decreasing integer timestamps representing event logs, calculate the maximum number of events that can take place within any closed interval of at most 60 units of time (i.e., $[T_{\text{start}}, T_{\text{start}} + 60]$ inclusive).
Two events occurring at timestamps $t_i$ and $t_j$ (where $t_j \ge t_i$) fall inside the same 60-second window if and only if $t_j - t_i \le 60$.
Constraints
- $0 \le \text{len(timestamps)} \le 10^5$
- $-10^9 \le \text{timestamps}[i] \le 10^9$
- The input list
timestampsis guaranteed to be sorted in non-decreasing order.
Examples
Example 1
Input: max_events_in_60_seconds([])
Output: 0
Example 2
Input: max_events_in_60_seconds([1])
Output: 1
Example 3
Input: max_events_in_60_seconds([1, 2, 3, 60, 61])
Output: 5
Example 4
Input: max_events_in_60_seconds([10, 20, 70, 70, 130])
Output: 4
Hints
Hint 1
Since the timestamps are sorted, can you use two pointers to keep track of the start and end of a valid time window?
Hint 2
If a window ending at index `right` spans more than 60 seconds from index `left`, how should `left` update?
Hint 3
Because each pointer only moves forward from 0 to N, what is the overall time complexity of this strategy?
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks for the maximum number of timestamps that can fit into an inclusive window of length 60 (that is, $t_{\text{end}} - t_{\text{start}} \le 60$).
Because the given sequence of timestamps is already sorted in non-decreasing order, we can use a two-pointer / sliding window approach:
- Maintain a pointer
leftindicating the start of our candidate window and iteraterightfrom $0$ to $N-1$ for the end of the window. - For each element at index
right, check if the differencetimestamps[right] - timestamps[left]exceeds 60. - If it exceeds 60, increment
leftuntil the conditiontimestamps[right] - timestamps[left] <= 60is satisfied. - The number of elements contained in the current valid window ending at
rightisright - left + 1. Track the maximum value observed across all steps.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of timestamps. Both
rightandlefttraverse the array at most once, resulting in linear runtime. - Space Complexity: $\mathcal{O}(1)$ auxiliary space as we only store integer variables for the window boundaries and maximum count.
Python Reference Solution
from typing import List
def max_events_in_60_seconds(timestamps: List[int]) -> int:
left = 0
max_count = 0
for right in range(len(timestamps)):
while timestamps[right] - timestamps[left] > 60:
left += 1
max_count = max(max_count, right - left + 1)
return max_count