KatInterview

Slice a Sorted Event Stream by Timestamp Window

Heaps, Sorting & SearchAuto-graded · 25 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharrayssorting

Last 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_start and window_end are 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_start is larger than every timestamp, where window_end is 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^5
  • 0 <= timestamp <= 10^9 for every event
  • events[i][0] <= events[i+1][0] for every valid i (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.