Filter Sorted Logs by Inclusive Time Window
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
An application holds a chronological log logs in memory as a list of (timestamp, message) tuples, where timestamp is an integer and message is a string. Entries are pre-sorted in non-decreasing order of timestamp, and multiple records can share identical timestamps (or identical messages).
Implement:
def logs_in_range(logs: list[tuple[int, str]], start_time: int, end_time: int) -> list[tuple[int, str]]:
Return all records from logs whose timestamp lies within [start_time, end_time].
Follow these rules:
- Inclusive window: Keep every entry
(t, msg)satisfyingstart_time <= t <= end_time. - Stable contiguous order: Preserve the exact order in which matching entries appear in
logs, including records that tie ontimestamp. - No deduplication or mutation: Emit each matching
(timestamp, message)pair as-is without removing duplicates, and do not mutatelogs. - Empty matches: Return
[]whenever zero records fall inside[start_time, end_time](for instance, whenlogsis empty,start_timeexceeds the final timestamp,end_timeprecedes the earliest timestamp, or the window lands strictly between adjacent timestamps).
Examples
Example 1
Input:
logs = [(10, "init"), (20, "auth"), (20, "sync"), (35, "done"), (50, "idle")]
start_time = 20, end_time = 35
Output: [(20, "auth"), (20, "sync"), (35, "done")]
Both entries at timestamp 20 and the entry at timestamp 35 satisfy 20 <= t <= 35 and retain their original relative order.
Example 2
Input:
logs = [(12, "open"), (25, "ping"), (40, "close")]
start_time = 45, end_time = 60
Output: []
Because 45 is strictly larger than the latest timestamp 40, no record falls inside the window.
Example 3
Input:
logs = [(15, "queued"), (15, "queued"), (30, "sent"), (45, "ack")]
start_time = 5, end_time = 15
Output: [(15, "queued"), (15, "queued")]
The upper bound 15 equals the first timestamp in logs, and both identical (15, "queued") records are preserved without deduplication.
Constraints
0 <= len(logs) <= 10^50 <= timestamp <= 10^9(32-bit signed integer range)logs[i][0] <= logs[i + 1][0]for every0 <= i < len(logs) - 10 <= start_time <= end_time <= 10^9- Each
messagehas length1to100printable ASCII characters.
Step-by-step walkthrough
Understand the goal and input shape
We are given
logs, an in-memory list of(timestamp, message)pairs already sorted bytimestampin non-decreasing order, along with two integer boundsstart_time <= end_time. We want to return every entry whose timestamptsatisfiesstart_time <= t <= end_time, keeping the original order and keeping all duplicates.Because
logsis already sorted by timestamp, every matching entry sits next to every other matching entry in one unbroken block:index: 0 1 2 3 4 logs: [(10, "init"), (20, "auth"), (20, "sync"), (35, "done"), (50, "idle")] ^ ^ start_index = 1 stop_index = 4 |<--------- matching slice [1:4] -------->|That means the answer is always a single list slice
logs[start_index:stop_index](which is empty wheneverstart_index == stop_index). Our whole task reduces to finding the two cut indicesstart_indexandstop_index.Start with a linear scan (and why we can do better)
The most direct way to filter the log is to inspect every entry from left to right and keep the ones inside
[start_time, end_time]:def logs_in_range_scan(logs: list[tuple[int, str]], start_time: int, end_time: int) -> list[tuple[int, str]]: result = [] for entry in logs: timestamp = entry[0] if start_time <= timestamp <= end_time: result.append(entry) return resultThis scan is easy to read and great for testing, but it always checks all
nentries even if only two entries match. Becauselogsis sorted, we can skip whole halves of the list at a time using binary search (repeatedly checking the middle element of the remaining search range to throw away half the candidates), finding each cut index inO(log n)steps instead ofO(n).Key idea: turn an inclusive range into two "first at or after" cuts
Beginners often write two slightly different binary searches — one for the left boundary and one for the right boundary — and run into off-by-one bugs when duplicate timestamps appear. We can avoid that trap completely by defining one clean question:
first_index_at_or_after(logs, target_time): What is the smallest indexiwithlogs[i][0] >= target_time(orlen(logs)if every entry is earlier thantarget_time)?Now look at how that single helper locates both ends of our slice:
- Left cut (
start_index): We want the first entry withtimestamp >= start_time. Everything beforestart_indexhastimestamp < start_time, so it is too early. - Right cut (
stop_index): Python sliceslogs[start_index:stop_index]stop just beforestop_index, sostop_indexshould be the first entry that is too late, meaningtimestamp > end_time. Because every timestamp and bound is an integer, "timestamp > end_time" is the exact same condition as "timestamp >= end_time + 1"!
timestamps: [ 10, 20, 20, 35, 35, 50 ] indices: 0 1 2 3 4 5 ^ ^ first t >= 20 is index 1 first t >= 35 + 1 (i.e. t >= 36) is index 5 |<---- slice [1:5] ---->| (keeps all 20s and all 35s!)Notice how duplicates behave automatically:
start_indexlands on the very first copy ofstart_time, andstop_indexlands just past the last copy ofend_time.- Left cut (
Write the binary search helper
To write
first_index_at_or_afterwithout off-by-one mistakes, we maintain a half-open search window[left, right)with a clear loop invariant (a rule that stays true at the start of every loop iteration):- Every index strictly below
lefthastimestamp < target_time(definitely too early). - Every index at or above
righthastimestamp >= target_time(at or after our target).
Why start
rightatlen(logs)instead oflen(logs) - 1? Because if every entry inlogshastimestamp < target_time, there is no valid entry inside0 .. len(logs) - 1, and the answer must belen(logs). Startingright = len(logs)keepslen(logs)reachable without any specialifcheck!At each step while
left < right, we checkmid = (left + right) // 2: - Iflogs[mid][0] < target_time, indexmidis too early, so the answer must be atmid + 1or higher (left = mid + 1). - Otherwise (logs[mid][0] >= target_time), indexmidmight be the first valid entry, so we keepmidas a candidate by settingright = mid.Because
(left + right) // 2always rounds down towardleft,midis strictly less thanrightwheneverleft < right, so every step shrinks the window untilleft == right.def first_index_at_or_after(logs: list[tuple[int, str]], target_time: int) -> int: """Return the smallest index i with logs[i][0] >= target_time, or len(logs) if none exists.""" # Half-open search window [left, right): # - Every index < left is known to have timestamp < target_time. # - Every index >= right is known to have timestamp >= target_time. # Starting right at len(logs) (one past the last index) lets us return len(logs) # naturally when every entry in logs is strictly earlier than target_time. left = 0 right = len(logs) while left < right: mid = (left + right) // 2 mid_time = logs[mid][0] if mid_time < target_time: # mid is still too early, so the first valid index must be strictly right of mid. left = mid + 1 else: # mid_time >= target_time: mid could be the first valid index, # so keep mid inside the search window by pulling right down to mid. right = mid return left- Every index strictly below
Slice the matching range
With
first_index_at_or_afterready,logs_in_rangetakes just three clear steps: findstart_index, findstop_index, and returnlogs[start_index:stop_index].Slicing creates a new shallow list containing the original
(timestamp, message)pairs, sologsitself is never modified, duplicate messages are preserved, and any miss (logsis empty,end_timeis before the first entry,start_timeis past the last entry, or the range falls in a gap between two timestamps) producesstart_index == stop_index, which slices to[].def logs_in_range(logs: list[tuple[int, str]], start_time: int, end_time: int) -> list[tuple[int, str]]: # logs: sorted list of (timestamp, message) pairs, e.g. [(10, "init"), (20, "auth")]. # Phase 1: Find the first index whose timestamp is >= start_time. start_index = first_index_at_or_after(logs, start_time) # Phase 2: Find the first index whose timestamp is strictly > end_time. # Because timestamps are integers, "timestamp > end_time" is equivalent to # "timestamp >= end_time + 1", allowing us to reuse the exact same search helper. stop_index = first_index_at_or_after(logs, end_time + 1) # Phase 3: Slice out the contiguous window without modifying logs. # When nothing matches, start_index == stop_index and Python returns []. return logs[start_index:stop_index]Trace Example 1 step by step
Let's trace
logs = [(10, "init"), (20, "auth"), (20, "sync"), (35, "done"), (50, "idle")](len = 5) withstart_time = 20andend_time = 35:Search 1: first_index_at_or_after(logs, target_time = 20) left = 0, right = 5 -> mid = 2, mid_time = 20 >= 20 -> right = 2 left = 0, right = 2 -> mid = 1, mid_time = 20 >= 20 -> right = 1 left = 0, right = 1 -> mid = 0, mid_time = 10 < 20 -> left = 1 left == right == 1 -> returns start_index = 1 Search 2: first_index_at_or_after(logs, target_time = 35 + 1 = 36) left = 0, right = 5 -> mid = 2, mid_time = 20 < 36 -> left = 3 left = 3, right = 5 -> mid = 4, mid_time = 50 >= 36 -> right = 4 left = 3, right = 4 -> mid = 3, mid_time = 35 < 36 -> left = 4 left == right == 4 -> returns stop_index = 4 Result: logs[1:4] = [(20, "auth"), (20, "sync"), (35, "done")]Notice in Search 1 how landing on
mid = 2(the second entry at timestamp20) did not stop the loop — pullingright = 2forced the search to keep checking earlier indices until it found the first20at index1.In Example 2 (
[(12, "open"), (25, "ping"), (40, "close")]with45..60), both searches return3(len(logs)), andlogs[3:3]is[]. In Example 3 ([(15, "queued"), (15, "queued"), (30, "sent"), (45, "ack")]with5..15),start_index = 0andstop_index = 2, returning[(15, "queued"), (15, "queued")].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def first_index_at_or_after(logs: list[tuple[int, str]], target_time: int) -> int: """Return the smallest index i with logs[i][0] >= target_time, or len(logs) if none exists.""" # Half-open search window [left, right): # - Every index < left is known to have timestamp < target_time. # - Every index >= right is known to have timestamp >= target_time. # Starting right at len(logs) (one past the last index) lets us return len(logs) # naturally when every entry in logs is strictly earlier than target_time. left = 0 right = len(logs) while left < right: mid = (left + right) // 2 mid_time = logs[mid][0] if mid_time < target_time: # mid is still too early, so the first valid index must be strictly right of mid. left = mid + 1 else: # mid_time >= target_time: mid could be the first valid index, # so keep mid inside the search window by pulling right down to mid. right = mid return left def logs_in_range(logs: list[tuple[int, str]], start_time: int, end_time: int) -> list[tuple[int, str]]: # logs: sorted list of (timestamp, message) pairs, e.g. [(10, "init"), (20, "auth")]. # Phase 1: Find the first index whose timestamp is >= start_time. start_index = first_index_at_or_after(logs, start_time) # Phase 2: Find the first index whose timestamp is strictly > end_time. # Because timestamps are integers, "timestamp > end_time" is equivalent to # "timestamp >= end_time + 1", allowing us to reuse the exact same search helper. stop_index = first_index_at_or_after(logs, end_time + 1) # Phase 3: Slice out the contiguous window without modifying logs. # When nothing matches, start_index == stop_index and Python returns []. return logs[start_index:stop_index]✅ Submit now — all tests should pass.
Intuition & how it works
Think of logs like a thick, chronological paper ledger where thousands of events are printed in timestamp order. If someone asks you for every event between t = 20 and t = 35, you do not read from page 1 line by line — instead, you open the ledger in the middle, check the timestamp, and repeatedly discard whichever half is too early or too late. That halving strategy is called binary search (a search algorithm on sorted data that checks the middle item and eliminates half of the remaining items at each step). Because all matching entries sit in one contiguous block, we only need to place two bookmarks: one right before the first entry at or after start_time, and a second right after the last entry at or before end_time.
The naive approach scans the entire list from index 0 to len(logs) - 1 and keeps entries with start_time <= timestamp <= end_time. While a linear scan is simple, it inspects all n entries even when a query asks for a narrow window in a 100,000-line log. When a service answers many time-window queries against the same in-memory log, scanning everything each time wastes huge amounts of work compared to jumping straight to the two boundaries.
Let's trace Example 1: logs = [(10, "init"), (20, "auth"), (20, "sync"), (35, "done"), (50, "idle")] with start_time = 20 and end_time = 35.
- First, we binary-search for the earliest index with timestamp >= 20. Even when our first midpoint lands on index 2 ((20, "sync")), we keep searching leftward and find index 1 ((20, "auth")).
- Next, we want the first index strictly past 35. Because timestamps are integers, "timestamp > 35" is the exact same rule as "timestamp >= 36", so we run the exact same binary search for 36 and land on index 4 ((50, "idle")).
- Finally, slicing logs[1:4] returns [(20, "auth"), (20, "sync"), (35, "done")] — keeping both entries at 20 in their original order and including 35.
Complexity
- Time:
O(log n + k), wherenislen(logs)andkis the number of matching entries returned. Each of the two binary searches halves ann-element index window until one index remains, takingO(log n)comparisons, and slicinglogs[start_index:stop_index]copieskreferences into the output list inO(k)time. (If a caller only needed the count of matching logs or the(start_index, stop_index)index pair, skipping the slice would make the entire queryO(log n).) - Space:
O(k)for the returned list slice, andO(1)auxiliary workspace because the binary search only tracks a few integer index variables (left,right,mid).
Edge cases
- Empty log (
logs = []): Both binary searches immediately start withleft = 0, right = 0and return0, sologs[0:0]cleanly returns[]. - Range completely before or after all logs: If
end_timeis smaller thanlogs[0][0], both searches return0; ifstart_timeis larger thanlogs[-1][0], both searches returnlen(logs). Either waystart_index == stop_indexand the result is[]. - Range inside a gap between timestamps: For
[(1, "a"), (10, "b")]with range3..8, both>= 3and>= 9land on index1, returninglogs[1:1] == []. - Single-point range (
start_time == end_time):start_indexfinds the first entry>= tandstop_indexfinds the first entry>= t + 1, returning every log at timestampt(or[]if none exist). - Duplicate timestamps and identical
(timestamp, message)pairs: Becausestart_indexstops before the first copy ofstart_timeandstop_indexstops after the last copy ofend_time, every duplicate is kept in its exact original order without deduplication. - Maximum timestamp (
end_time = 10^9): Python integers have arbitrary precision, soend_time + 1never overflows (and even in a 32-bit signed integer language,10^9 + 1is well below2^31 - 1 = 2,147,483,647).
Common mistakes
- Searching for
end_timeinstead ofend_time + 1on the upper cut: Callingfirst_index_at_or_after(logs, end_time)stops before entries whose timestamp equalsend_time, turning an inclusive upper bound into an exclusive one and dropping valid entries. - Returning immediately when
logs[mid][0] == target_time: A textbook "does this number exist?" binary search stops at whichever duplicate it hits first, slicing right through the middle of a group of equal timestamps. You must keep narrowing[left, right)so you land on the boundary of the duplicate group. - Initializing
right = len(logs) - 1instead oflen(logs): In a half-open interval[left, right)(a range that includesleftand excludesright), settingright = len(logs) - 1makes indexlen(logs)impossible to return. Wheneverend_timecovers the last element oflogs,stop_indexgets stuck atlen(logs) - 1andlogs[start_index:stop_index]silently drops the final log entry. - Comparing whole
(timestamp, message)tuples instead ofentry[0]: Writingbisect_right(logs, (end_time, ""))fails in two ways: first,(35, "done") > (35, "")causes entries atend_timeto be excluded; second, if test inputs pass[timestamp, message]lists instead of tuples, comparing alistto atupleraisesTypeErrorin Python. Always compareentry[0]alone.
Alternative approaches
- Python's
bisectmodule (Python 3.10+): Python's standard library providesbisect_leftandbisect_right(built-in binary search helpers that find insertion points before or after equal elements). Withkey=lambda entry: entry[0],bisect_left(logs, start_time, key=...)computesstart_indexandbisect_right(logs, end_time, key=...)computesstop_indexwithout needingend_time + 1— which is also the right pattern when timestamps are floating-point numbers rather than integers. Writing the 15-line helper explicitly is preferred in interviews because many interviewers ask to see the boundary logic without library helpers. - Separate
first_index_afterhelper for non-integer timestamps: If timestamps could be floats (like3.14159),end_time + 1would skip values like5.5. In that case, write a twin helper whereif mid_time <= target_time: left = mid + 1to find the first index strictly greater thanend_time.
Follow-up questions
- How would you answer time-window queries if the sorted log is a 500 GB file on disk that cannot fit in memory? Binary-search directly over file byte offsets instead of list indices. Seek to the midpoint byte
(low_byte + high_byte) // 2, scan forward to the next newline\nso you land at the start of a complete log line, parse that line's timestamp, and narrow[low_byte, high_byte). Once you locate the byte offset of the first matching record inO(log(file_size))disk seeks, stream lines sequentially until a timestamp exceedsend_time. - How does your design change if new log records arrive continuously in real time? If records arrive in non-decreasing timestamp order, appending to the end of
logsinO(1)amortized time keeps the list sorted, so the exact samelogs_in_rangefunction keeps working with zero changes. If network delays cause records to arrive slightly out of order, keep a small recent buffer that gets sorted on flush or store chunks in a balanced search tree (a tree data structure that keeps items sorted while supportingO(log n)insertions and range lookups). - How would you compute per-minute event counts over [start_time, end_time] without copying the matching slice? Use the same two binary searches to find
start_indexandstop_indexinO(log n)time, then iterate overrange(start_index, stop_index)directly and incrementcounts[logs[i][0] // 60](assuming timestamps are in seconds). That runs inO(log n + k)time andO(m)space formactive minutes rather than allocating ak-element slice.
Follow-up questions
- How would you answer time-window queries if the sorted log is a 500 GB file on disk that cannot fit in memory?
- How does your design change if new log records arrive continuously in real time?
- How would you compute per-minute event counts over [start_time, end_time] without copying the matching slice?
Similar questions
- Scoped S-Expression Arithmetic Evaluator
- Inclusive Index Bounds for Sorted Timestamp Queries
- Repeatedly Collapse K-Length Character Runs
- Rate-Capped Third-Party API Sync Service
- Kafka-Backed Event Analytics Pipeline and Long-Term Warehouse
- Merchant Snapshot Catalog with Admin Attribute Overrides
More Attentive interview questions
- Merchant Snapshot Catalog with Admin Attribute Overrides Medium
- Multi-Tenant Scheduled Broadcast Messaging Service Medium
- Streaming Large-Object Text Reduction Service Medium Pro
- Rate-Capped Third-Party API Sync Service Medium Pro
- Fault-Tolerant External API Ingestion Platform Medium Pro
- High-Throughput Versioned Product Catalog Service Medium Pro
- Prefix Expression Evaluator with ADD, MULT, and Scoped LET Medium Pro
- Scoped S-Expression Arithmetic Evaluator Medium Pro
- Inclusive Index Bounds for Sorted Timestamp Queries Medium Pro
- Time-Series Storage Backend for High-Cardinality Metrics Medium Pro