KatInterview

Find Peak Event Density in Fixed Duration Window

Greedy & IntervalsAuto-graded · 24 test cases
EasyAuto-gradedGreedy & Intervalssliding-windowtwo-pointersarrays

Last 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 timestamps is 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?