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 start and start + 60 belong to the range, meaning two events separated by 60 seconds fit in the same range while two events separated by 61 seconds do not.
  • Equal values in timestamps represent distinct simultaneous events and each one adds 1 to the count.
  • When timestamps is empty, return 0.

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^9
  • timestamps is sorted in non-decreasing order.

Step-by-step walkthrough

  1. Understand the goal and the closed-interval rule

    We receive a list timestamps of 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 returns 0.

  2. Why checking every second or restarting from every event is too slow

    Two obvious approaches run into trouble at scale: 1. Try every integer start from min(timestamps) to max(timestamps): if two events happen a year apart (31,536,000 seconds) or use Unix epoch values, stepping through every clock second wastes millions of iterations on empty gaps. 2. Start a fresh loop at every event i and scan forward while timestamps[j] - timestamps[i] <= 60: if 100,000 events all cluster inside the same minute, every inner scan walks almost the entire remaining list, taking O(n^2) time (~5 billion checks). Even replacing the inner scan with binary search still costs O(n log n) time because it ignores the overlap between adjacent windows.

  3. Key idea: anchor the window on its rightmost event

    Take any optimal range [start, start + 60] that holds at least one event, and let right be the index of the last event inside it. Now slide that range backward until its right edge sits directly on timestamps[right], turning it into [timestamps[right] - 60, timestamps[right]]: - We do not lose any events on the right (there were none between timestamps[right] and start + 60 anyway). - Sliding left only extends coverage earlier, so we never lose events on the left either.

    Therefore, checking [timestamps[right] - 60, timestamps[right]] for every index right is guaranteed to find the global maximum! And because timestamps is sorted: - All events up to right that fall in [timestamps[right] - 60, timestamps[right]] form one contiguous slice left .. right, containing right - left + 1 events. - As right steps forward, timestamps[right] - 60 never decreases, so left only 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      right
    
  4. Write the two-pointer loop

    For each right from 0 to len(timestamps) - 1, we advance left while timestamps[right] - timestamps[left] > 60: - Notice the strict > (not >=): when timestamps[right] - timestamps[left] == 60, both endpoints belong to [timestamps[left], timestamps[left] + 60], so left stays inside. - Can left ever run past right and go out of bounds? Never: when left == right, the difference timestamps[right] - timestamps[right] is 0, which is not > 60, so the while loop always stops at left <= right. - What if duplicate timestamps sit right after right (like [4, 18, 64, 64])? At right = 2 (64) we count 3, and on the very next iteration right = 3 (64) we include the duplicate and count 4!

    Only three integer variables (max_count, left, window_count) are needed besides the loop index right, achieving O(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_count
    
  5. Trace 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], holding 4 events (4, 18, 64, 64).

  6. 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), where n is len(timestamps). The outer loop advances right n times, and across the entire function call left only increments forward and never passes right, so the inner while loop executes at most n increments total (amortized O(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, and window_count) and read timestamps in place without copying or mutating it.

Edge cases

  • Empty list ([]): the for loop never executes and max_count returns 0.
  • Single event ([42]): left = 0, right = 0, returning 1.
  • Exact 60-second boundary ([0, 60] vs [0, 61]): 60 - 0 == 60 is not > 60, so [0, 60] returns 2, whereas 61 - 0 == 61 > 60 advances left and returns 1.
  • Duplicate timestamps ([5, 5, 5, 5]): index arithmetic right - left + 1 treats every array entry as a distinct event, returning 4.
  • Negative or Unix-epoch timestamps ([-20, 50, 55, 110] or 1.7 * 10^9): only pairwise differences timestamps[right] - timestamps[left] are computed, so negative and large positive integers work identically.

Common mistakes

  • Using >= 60 instead of > 60 in the while condition: >= 60 models a half-open interval [a, a + 60) of 60 discrete integer ticks (a through a + 59) rather than the closed interval [a, a + 60], returning 4 instead of 5 on [5, 12, 25, 64, 65].
  • Resetting left on every iteration (or scanning backward from right): recomputing the window boundary from scratch turns an O(n) pass into O(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 seconds 59 and 61 (only 2 seconds apart, yet split into buckets 0 and 1).
  • 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 by 60 seconds do not fit together, change the shrink check from > 60 to >= 60. For an arbitrary non-negative window width W, replace the literal 60 with W; time stays O(n) and auxiliary space stays O(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) uses O(n) extra space while preserving the caller's list, whereas timestamps.sort() mutates in place). If all timestamps fall within a small bounded span R (say, one day = 86,400 seconds), counting events per second in an array of length R + 1 and sliding a 61-slot running sum finds the answer in O(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 - 60 from the left in O(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 by t % 61 storing (second, count) per slot alongside a running sum) for strict O(1) memory regardless of burst rate.

Follow-up questions

Similar questions

More Marshall Wace interview questions

All 2 Marshall Wace questions →