Slice a Sorted Event Stream by Timestamp Window
Heaps, Sorting & SearchAuto-graded · 25 test casesLast updated
Tests binary search boundary reasoning on a sorted sequence with duplicate timestamps and inclusive range semantics.
Problem
You have a sequence of timestamped events already loaded into memory. Each event is a pair (timestamp, message), where timestamp is a non-negative integer and message is a string. The sequence is sorted in non-decreasing order of timestamp, and multiple events may share the same timestamp.
Given two integers window_start and window_end, return every event whose timestamp t satisfies window_start <= t <= window_end.
Rules
- Both
window_startandwindow_endare inclusive bounds. - Return matching events in the same order they appear in the input. Because the input is sorted, all matching events form a single contiguous block, and that block in its original order is the unique correct answer.
- Return each event as an unchanged
(timestamp, message)pair. Do not deduplicate: if two events have the same timestamp and the same message, both appear in the output. - Return an empty list if no event falls within the window. This covers the case where the input is empty, where
window_startis larger than every timestamp, wherewindow_endis smaller than every timestamp, and where the window falls entirely in a gap between timestamps. - Do not modify the input sequence.
Constraints
0 <= len(events) <= 10^50 <= timestamp <= 10^9for every eventevents[i][0] <= events[i+1][0]for every validi(non-decreasing order)0 <= window_start <= window_end <= 10^9- Each message is a non-empty string of at most 100 printable ASCII characters; messages need not be distinct.
- All timestamps and window bounds fit in a 32-bit signed integer.
Examples
Example 1
Input: logs_in_range([[1, 'boot'], [3, 'connect'], [3, 'retry'], [5, 'ready'], [8, 'shutdown']], 3, 5)
Output: [[3, 'connect'], [3, 'retry'], [5, 'ready']]
Example 2
Input: logs_in_range([[2, 'a'], [4, 'b'], [6, 'c']], 7, 10)
Output: []
Example 3
Input: logs_in_range([[2, 'a'], [2, 'b'], [4, 'c'], [6, 'd']], 0, 2)
Output: [[2, 'a'], [2, 'b']]
Hints
Hint 1
Because the input is sorted, all matching events sit in one contiguous block. You only need to find where that block starts and where it ends — you don't need to inspect every element.
Hint 2
Think about two separate searches: one that locates the first event with timestamp >= window_start, and one that locates the first event with timestamp > window_end. The answer is everything between those two positions.
Hint 3
Be careful about which comparison operator you use in each search. Using < versus <= determines whether duplicates exactly at a boundary are included or excluded — and both boundaries must be inclusive.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because events is sorted by timestamp, every event that falls within [window_start, window_end] forms one contiguous block. Finding that block requires only two boundary positions:
- Left boundary
a: the index of the first event with timestamp>= window_start(classic lower bound). - Right boundary
b: the index of the first event with timestamp> window_end(classic upper bound).
The answer is then events[a:b]. If a >= b, the slice is empty and there are no matches.
Why each search is correct
Lower bound. The loop maintains the invariant that every index >= hi has timestamp >= window_start, and every index < lo has timestamp < window_start.
- If
events[mid][0] < window_start, thenmidand everything before it is too early, solo = mid + 1. - Otherwise
midis a valid candidate, sohi = mid.
When lo == hi, that index is exactly the first one satisfying the predicate. All duplicates at window_start are captured because we stop at the first of them.
Upper bound. The structure mirrors the lower bound, with the predicate flipped to <= window_end.
- If
events[mid][0] <= window_end, thenmidis still inside the window, solo = mid + 1. - Otherwise
midis the first position past the window, sohi = mid.
Using <= here (rather than <) means the search stops after all duplicates at window_end, so every event with that timestamp is included.
The second search safely starts at a rather than 0, because everything before a has timestamp < window_start <= window_end, which cannot be the upper boundary.
Edge cases
| Situation | Result |
|---|---|
events is empty | a = 0, b = 0 → [] |
window_start exceeds every timestamp | a = len(events) → empty slice |
window_end is below every timestamp | a = 0, b = 0 → [] |
| Window falls in a gap | a == b → [] |
window_start == window_end | Returns the full run of events at that exact timestamp |
| Duplicates at a boundary | Lower/upper bound capture the entire run on both sides |
| Window covers all events | a = 0, b = len(events) → full list |
No extra if guards are needed; the half-open [lo, hi) template handles every case uniformly.
Complexity
- Time:
O(log n + k), wherenis the length ofeventsandkis the number of matching events. The two binary searches costO(log n)each, and building the output slice costsO(k). No algorithm can do better thanO(k)since it must produce the output. - Space:
O(k)for the returned list;O(1)auxiliary space. The input is never modified.
A linear scan is O(n) and correct, but it ignores the sorted structure. For large inputs or repeated queries, the binary search approach is significantly faster.
Reference solution
from typing import List, Tuple
def logs_in_range(events: List[Tuple[int, str]], window_start: int, window_end: int) -> List[Tuple[int, str]]:
# First search: lower bound — first index with timestamp >= window_start.
# Invariant: everything at index >= hi has timestamp >= window_start.
lo, hi = 0, len(events)
while lo < hi:
mid = (lo + hi) // 2
if events[mid][0] < window_start:
lo = mid + 1 # mid is too early; discard it and everything before
else:
hi = mid # mid is a candidate; keep it in range
a = lo # first index inside the window (or len(events) if none)
# Second search: upper bound — first index with timestamp > window_end.
# Searching from a is safe: everything before a has timestamp < window_start <= window_end.
# Invariant: everything at index >= hi has timestamp > window_end.
lo, hi = a, len(events)
while lo < hi:
mid = (lo + hi) // 2
if events[mid][0] <= window_end:
lo = mid + 1 # mid is still inside the window; move past it
else:
hi = mid # mid is past the window; keep it as the boundary
# lo is now the first index past the window
return [[e[0], e[1]] for e in events[a:lo]]