Busiest 60-Second Event Window
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given an integer array timestamps sorted in non-decreasing order (timestamps[0] <= timestamps[1] <= ...), where each element records the second at which an event happened.
Compute the largest number of events that fall inside any single closed 60-second range [start, start + 60]:
- Both endpoints
startandstart + 60belong to the range, meaning two events separated by60seconds fit in the same range while two events separated by61seconds do not. - Equal values in
timestampsrepresent distinct simultaneous events and each one adds1to the count. - When
timestampsis empty, return0.
Your solution should run in O(n) time and use O(1) auxiliary space.
Examples
Example 1
Input: timestamps = [5, 12, 25, 64, 65]
Output: 5
Walk-through: Choosing start = 5 gives the closed range [5, 65]. Since 65 - 5 = 60, all 5 events lie inside [5, 65].
Example 2
Input: timestamps = [4, 18, 64, 64, 80, 125]
Output: 4
Walk-through: The range [4, 64] captures four events (4, 18, 64, 64). Later ranges such as [20, 80] (64, 64, 80) or [65, 125] (80, 125, since 125 - 64 = 61 > 60) capture at most 3 events.
Example 3
Input: timestamps = [15, 90, 160]
Output: 1
Walk-through: Adjacent events are 75 and 70 seconds apart, so no [start, start + 60] range can cover two events at once.
Example 4
Input: timestamps = [-20, 50, 55, 110]
Output: 3
Walk-through: Negative timestamps behave like any other integer second. The range [50, 110] holds the three events 50, 55, 110.
Constraints
0 <= len(timestamps) <= 10^5-10^9 <= timestamps[i] <= 10^9timestampsis sorted in non-decreasing order.
Step-by-step walkthrough
Understand the goal and the closed-interval rule
We receive a list
timestampsof integer seconds sorted in non-decreasing order (timestamps[0] <= timestamps[1] <= ...). Multiple entries may share the exact same second, and each entry counts as a separate event. We want the largest count of events that fit inside any single closed range[start, start + 60].Example 1: timestamps = [5, 12, 25, 64, 65] Timeline: 5 12 25 ... 64 65 [----------------------------------------] start = 5 start + 60 = 65 Span = 65 - 5 = 60 <= 60 --> all 5 events fit!Two events belong to a common range if and only if
latest_timestamp - earliest_timestamp <= 60. An empty input returns0.Why checking every second or restarting from every event is too slow
Two obvious approaches run into trouble at scale: 1. Try every integer
startfrommin(timestamps)tomax(timestamps): if two events happen a year apart (31,536,000seconds) or use Unix epoch values, stepping through every clock second wastes millions of iterations on empty gaps. 2. Start a fresh loop at every eventiand scan forward whiletimestamps[j] - timestamps[i] <= 60: if100,000events all cluster inside the same minute, every inner scan walks almost the entire remaining list, takingO(n^2)time (~5 billion checks). Even replacing the inner scan with binary search still costsO(n log n)time because it ignores the overlap between adjacent windows.Key idea: anchor the window on its rightmost event
Take any optimal range
[start, start + 60]that holds at least one event, and letrightbe the index of the last event inside it. Now slide that range backward until its right edge sits directly ontimestamps[right], turning it into[timestamps[right] - 60, timestamps[right]]: - We do not lose any events on the right (there were none betweentimestamps[right]andstart + 60anyway). - Sliding left only extends coverage earlier, so we never lose events on the left either.Therefore, checking
[timestamps[right] - 60, timestamps[right]]for every indexrightis guaranteed to find the global maximum! And becausetimestampsis sorted: - All events up torightthat fall in[timestamps[right] - 60, timestamps[right]]form one contiguous sliceleft .. right, containingright - left + 1events. - Asrightsteps forward,timestamps[right] - 60never decreases, soleftonly ever moves forward—never backward!right = 3 (t = 64), window [4, 64]: [4, 18, 64, 64], 80, 125 (left = 0, count = 4) ^ ^ left right right = 4 (t = 80), window [20, 80]: 4, 18, [64, 64, 80], 125 (left advances to 2, count = 3) ^ ^ left rightWrite the two-pointer loop
For each
rightfrom0tolen(timestamps) - 1, we advanceleftwhiletimestamps[right] - timestamps[left] > 60: - Notice the strict>(not>=): whentimestamps[right] - timestamps[left] == 60, both endpoints belong to[timestamps[left], timestamps[left] + 60], soleftstays inside. - Canleftever run pastrightand go out of bounds? Never: whenleft == right, the differencetimestamps[right] - timestamps[right]is0, which is not> 60, so thewhileloop always stops atleft <= right. - What if duplicate timestamps sit right afterright(like[4, 18, 64, 64])? Atright = 2(64) we count3, and on the very next iterationright = 3(64) we include the duplicate and count4!Only three integer variables (
max_count,left,window_count) are needed besides the loop indexright, achievingO(1)auxiliary space.def max_events_in_60_seconds(timestamps: List[int]) -> int: # max_count: largest number of events seen in any [start, start + 60] window so far. max_count = 0 # left: index of the earliest event still within 60 seconds of timestamps[right]. left = 0 # Phase 1: Treat each timestamps[right] as the right edge of window [t_right - 60, t_right]. for right in range(len(timestamps)): # Drop events strictly older than timestamps[right] - 60. # Strictly '>' (not '>=') because the window is inclusive: a gap of 60 fits inside. while timestamps[right] - timestamps[left] > 60: left += 1 # Phase 2: Because timestamps is sorted, every index in left..right falls inside the window. window_count = right - left + 1 if window_count > max_count: max_count = window_count return max_countTrace Example 2 step by step
Let's trace
timestamps = [4, 18, 64, 64, 80, 125]:right t[right] Valid range While loop (drop > 60s old) left Active slice count max ----- -------- ------------- -------------------------------- ---- ------------------ ----- --- 0 4 [-56, 4] 4 - 4 = 0 <= 60 (keep) 0 [4] 1 1 1 18 [-42, 18] 18 - 4 = 14 <= 60 (keep) 0 [4, 18] 2 2 2 64 [4, 64] 64 - 4 = 60 <= 60 (keep!) 0 [4, 18, 64] 3 3 3 64 [4, 64] 64 - 4 = 60 <= 60 (keep!) 0 [4, 18, 64, 64] 4 4 4 80 [20, 80] 80 - 4 = 76 > 60 -> left = 1 2 [64, 64, 80] 3 4 80 - 18 = 62 > 60 -> left = 2 80 - 64 = 16 <= 60 (stop) 5 125 [65, 125] 125 - 64 = 61 > 60 -> left = 3, 4 4 [80, 125] 2 4 125 - 80 = 45 <= 60 (stop)The busiest 60-second range is
[4, 64], holding4events (4, 18, 64, 64).Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def max_events_in_60_seconds(timestamps: List[int]) -> int: # max_count: largest number of events seen in any [start, start + 60] window so far. max_count = 0 # left: index of the earliest event still within 60 seconds of timestamps[right]. left = 0 # Phase 1: Treat each timestamps[right] as the right edge of window [t_right - 60, t_right]. for right in range(len(timestamps)): # Drop events strictly older than timestamps[right] - 60. # Strictly '>' (not '>=') because the window is inclusive: a gap of 60 fits inside. while timestamps[right] - timestamps[left] > 60: left += 1 # Phase 2: Because timestamps is sorted, every index in left..right falls inside the window. window_count = right - left + 1 if window_count > max_count: max_count = window_count return max_count✅ Submit now — all tests should pass.
Intuition & how it works
Picture laying a 60-second ruler along a sorted timeline of event marks: if you line up the right tip of the ruler with each event in turn, any event that falls off the left tip of the ruler will also fall off for every later event, because later events only push the ruler further right. That lets us use a two-pointer sliding window (two indices left and right bounding the active slice timestamps[left : right + 1] that both move only left-to-right across the array) without allocating any auxiliary data structures.
Why do simpler approaches fail? Looping over every clock second [a, a + 60] does work proportional to the time span rather than n, which crawls or times out when timestamps span days or years. Starting an inner scan at each event i to count events up to timestamps[i] + 60 re-scans overlapping ranges from scratch, taking O(n^2) time whenever tens of thousands of events cluster inside a single busy minute.
Walk through Example 2, timestamps = [4, 18, 64, 64, 80, 125]:
- right = 0 (4): left = 0, active slice [4] has 1 event (max_count = 1).
- right = 1 (18): 18 - 4 = 14 <= 60, left stays 0, slice [4, 18] has 2 events (max_count = 2).
- right = 2 (64): 64 - 4 = 60 <= 60, left stays 0, slice [4, 18, 64] has 3 events (max_count = 3).
- right = 3 (64): 64 - 4 = 60 <= 60, left stays 0, slice [4, 18, 64, 64] has 4 events (max_count = 4).
- right = 4 (80): 80 - 4 > 60 and 80 - 18 > 60, so left advances to 2 (64), giving 3 events.
- right = 5 (125): both 64s are 61 seconds older than 125, so left advances to 4 (80), giving 2 events; return max_count = 4.
Complexity
- Time:
O(n), wherenislen(timestamps). The outer loop advancesrightntimes, and across the entire function callleftonly increments forward and never passesright, so the innerwhileloop executes at mostnincrements total (amortizedO(1)per event, meaning the average cost per event over the whole run is constant). - Space:
O(1)auxiliary space. We only keep four scalar integers (max_count,left,right, andwindow_count) and readtimestampsin place without copying or mutating it.
Edge cases
- Empty list (
[]): theforloop never executes andmax_countreturns0. - Single event (
[42]):left = 0, right = 0, returning1. - Exact 60-second boundary (
[0, 60]vs[0, 61]):60 - 0 == 60is not> 60, so[0, 60]returns2, whereas61 - 0 == 61 > 60advancesleftand returns1. - Duplicate timestamps (
[5, 5, 5, 5]): index arithmeticright - left + 1treats every array entry as a distinct event, returning4. - Negative or Unix-epoch timestamps (
[-20, 50, 55, 110]or1.7 * 10^9): only pairwise differencestimestamps[right] - timestamps[left]are computed, so negative and large positive integers work identically.
Common mistakes
- Using
>= 60instead of> 60in thewhilecondition:>= 60models a half-open interval[a, a + 60)of 60 discrete integer ticks (athrougha + 59) rather than the closed interval[a, a + 60], returning4instead of5on[5, 12, 25, 64, 65]. - Resetting
lefton every iteration (or scanning backward fromright): recomputing the window boundary from scratch turns anO(n)pass intoO(n^2). - Partitioning timestamps into fixed 60-second calendar buckets (
t // 60): fixed buckets miss bursts that straddle a bucket boundary, such as events at seconds59and61(only2seconds apart, yet split into buckets0and1). - Deduplicating timestamps with a
set: collapsing simultaneous events undercounts bursts where multiple events share the same second.
Follow-up questions
- How does the condition change for a half-open window [start, start + 60) or a configurable duration W? For a half-open interval
[start, start + 60)where events separated by60seconds do not fit together, change the shrink check from> 60to>= 60. For an arbitrary non-negative window widthW, replace the literal60withW; time staysO(n)and auxiliary space staysO(1). - What would you do if the input timestamps were not sorted beforehand? Sort the timestamps first in
O(n log n)time and then run the same two-pointer sweep (sorted(timestamps)usesO(n)extra space while preserving the caller's list, whereastimestamps.sort()mutates in place). If all timestamps fall within a small bounded spanR(say, one day =86,400seconds), counting events per second in an array of lengthR + 1and sliding a 61-slot running sum finds the answer inO(n + R)time without comparison sorting. - How could you maintain the peak 60-second count over a live, unbounded stream of arriving timestamps? Because the full stream cannot stay in memory, maintain either a deque (a double-ended queue that appends new arrivals on the right and pops timestamps older than
t - 60from the left inO(1)amortized time, using memory proportional to the busiest minute) or, if dozens of millions of events can arrive per second, a 61-slot ring buffer (a fixed-size circular array indexed byt % 61storing(second, count)per slot alongside a running sum) for strictO(1)memory regardless of burst rate.
Follow-up questions
- How does the condition change for a half-open window [start, start + 60) or a configurable duration W?
- What would you do if the input timestamps were not sorted beforehand?
- How could you maintain the peak 60-second count over a live, unbounded stream of arriving timestamps?
Similar questions
- Users Signing In From Multiple Countries
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One