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) satisfying start_time <= t <= end_time.
  • Stable contiguous order: Preserve the exact order in which matching entries appear in logs, including records that tie on timestamp.
  • No deduplication or mutation: Emit each matching (timestamp, message) pair as-is without removing duplicates, and do not mutate logs.
  • Empty matches: Return [] whenever zero records fall inside [start_time, end_time] (for instance, when logs is empty, start_time exceeds the final timestamp, end_time precedes 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^5
  • 0 <= timestamp <= 10^9 (32-bit signed integer range)
  • logs[i][0] <= logs[i + 1][0] for every 0 <= i < len(logs) - 1
  • 0 <= start_time <= end_time <= 10^9
  • Each message has length 1 to 100 printable ASCII characters.

Step-by-step walkthrough

  1. Understand the goal and input shape

    We are given logs, an in-memory list of (timestamp, message) pairs already sorted by timestamp in non-decreasing order, along with two integer bounds start_time <= end_time. We want to return every entry whose timestamp t satisfies start_time <= t <= end_time, keeping the original order and keeping all duplicates.

    Because logs is 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 whenever start_index == stop_index). Our whole task reduces to finding the two cut indices start_index and stop_index.

  2. 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 result
    

    This scan is easy to read and great for testing, but it always checks all n entries even if only two entries match. Because logs is 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 in O(log n) steps instead of O(n).

  3. 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 index i with logs[i][0] >= target_time (or len(logs) if every entry is earlier than target_time)?

    Now look at how that single helper locates both ends of our slice:

    • Left cut (start_index): We want the first entry with timestamp >= start_time. Everything before start_index has timestamp < start_time, so it is too early.
    • Right cut (stop_index): Python slices logs[start_index:stop_index] stop just before stop_index, so stop_index should be the first entry that is too late, meaning timestamp > 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_index lands on the very first copy of start_time, and stop_index lands just past the last copy of end_time.

  4. Write the binary search helper

    To write first_index_at_or_after without 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):

    1. Every index strictly below left has timestamp < target_time (definitely too early).
    2. Every index at or above right has timestamp >= target_time (at or after our target).

    Why start right at len(logs) instead of len(logs) - 1? Because if every entry in logs has timestamp < target_time, there is no valid entry inside 0 .. len(logs) - 1, and the answer must be len(logs). Starting right = len(logs) keeps len(logs) reachable without any special if check!

    At each step while left < right, we check mid = (left + right) // 2: - If logs[mid][0] < target_time, index mid is too early, so the answer must be at mid + 1 or higher (left = mid + 1). - Otherwise (logs[mid][0] >= target_time), index mid might be the first valid entry, so we keep mid as a candidate by setting right = mid.

    Because (left + right) // 2 always rounds down toward left, mid is strictly less than right whenever left < right, so every step shrinks the window until left == 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
    
  5. Slice the matching range

    With first_index_at_or_after ready, logs_in_range takes just three clear steps: find start_index, find stop_index, and return logs[start_index:stop_index].

    Slicing creates a new shallow list containing the original (timestamp, message) pairs, so logs itself is never modified, duplicate messages are preserved, and any miss (logs is empty, end_time is before the first entry, start_time is past the last entry, or the range falls in a gap between two timestamps) produces start_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]
    
  6. Trace Example 1 step by step

    Let's trace logs = [(10, "init"), (20, "auth"), (20, "sync"), (35, "done"), (50, "idle")] (len = 5) with start_time = 20 and end_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 timestamp 20) did not stop the loop — pulling right = 2 forced the search to keep checking earlier indices until it found the first 20 at index 1.

    In Example 2 ([(12, "open"), (25, "ping"), (40, "close")] with 45..60), both searches return 3 (len(logs)), and logs[3:3] is []. In Example 3 ([(15, "queued"), (15, "queued"), (30, "sent"), (45, "ack")] with 5..15), start_index = 0 and stop_index = 2, returning [(15, "queued"), (15, "queued")].

  7. 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), where n is len(logs) and k is the number of matching entries returned. Each of the two binary searches halves an n-element index window until one index remains, taking O(log n) comparisons, and slicing logs[start_index:stop_index] copies k references into the output list in O(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 query O(log n).)
  • Space: O(k) for the returned list slice, and O(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 with left = 0, right = 0 and return 0, so logs[0:0] cleanly returns [].
  • Range completely before or after all logs: If end_time is smaller than logs[0][0], both searches return 0; if start_time is larger than logs[-1][0], both searches return len(logs). Either way start_index == stop_index and the result is [].
  • Range inside a gap between timestamps: For [(1, "a"), (10, "b")] with range 3..8, both >= 3 and >= 9 land on index 1, returning logs[1:1] == [].
  • Single-point range (start_time == end_time): start_index finds the first entry >= t and stop_index finds the first entry >= t + 1, returning every log at timestamp t (or [] if none exist).
  • Duplicate timestamps and identical (timestamp, message) pairs: Because start_index stops before the first copy of start_time and stop_index stops after the last copy of end_time, every duplicate is kept in its exact original order without deduplication.
  • Maximum timestamp (end_time = 10^9): Python integers have arbitrary precision, so end_time + 1 never overflows (and even in a 32-bit signed integer language, 10^9 + 1 is well below 2^31 - 1 = 2,147,483,647).

Common mistakes

  • Searching for end_time instead of end_time + 1 on the upper cut: Calling first_index_at_or_after(logs, end_time) stops before entries whose timestamp equals end_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) - 1 instead of len(logs): In a half-open interval [left, right) (a range that includes left and excludes right), setting right = len(logs) - 1 makes index len(logs) impossible to return. Whenever end_time covers the last element of logs, stop_index gets stuck at len(logs) - 1 and logs[start_index:stop_index] silently drops the final log entry.
  • Comparing whole (timestamp, message) tuples instead of entry[0]: Writing bisect_right(logs, (end_time, "")) fails in two ways: first, (35, "done") > (35, "") causes entries at end_time to be excluded; second, if test inputs pass [timestamp, message] lists instead of tuples, comparing a list to a tuple raises TypeError in Python. Always compare entry[0] alone.

Alternative approaches

  • Python's bisect module (Python 3.10+): Python's standard library provides bisect_left and bisect_right (built-in binary search helpers that find insertion points before or after equal elements). With key=lambda entry: entry[0], bisect_left(logs, start_time, key=...) computes start_index and bisect_right(logs, end_time, key=...) computes stop_index without needing end_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_after helper for non-integer timestamps: If timestamps could be floats (like 3.14159), end_time + 1 would skip values like 5.5. In that case, write a twin helper where if mid_time <= target_time: left = mid + 1 to find the first index strictly greater than end_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 \n so 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 in O(log(file_size)) disk seeks, stream lines sequentially until a timestamp exceeds end_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 logs in O(1) amortized time keeps the list sorted, so the exact same logs_in_range function 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 supporting O(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_index and stop_index in O(log n) time, then iterate over range(start_index, stop_index) directly and increment counts[logs[i][0] // 60] (assuming timestamps are in seconds). That runs in O(log n + k) time and O(m) space for m active minutes rather than allocating a k-element slice.

Follow-up questions

Similar questions

More Attentive interview questions

All 16 Attentive questions →