Return Log Entries Within an Inclusive Time Range From a Sorted Log
AttentiveSoftware Engineer · OnsiteLast updated
Given an in-memory log sorted by integer timestamp, return every entry whose timestamp lies within an inclusive start and end time. The problem tests exact boundary handling with duplicate timestamps, empty results when the range misses the log, and locating a range efficiently in sorted data.
You are given a log that has already been loaded into memory as a list of entries. Each entry is a pair (timestamp, message), where timestamp is an integer and message is a string. The entries are sorted by timestamp in non-decreasing order, and several entries may share the same timestamp.
Given start_time and end_time, return every entry whose timestamp t satisfies start_time <= t <= end_time.
Function Signature
def logs_in_range(logs: list[tuple[int, str]], start_time: int, end_time: int) -> list[tuple[int, str]]:
Rules
- Both bounds are inclusive.
- Return the matching entries in the same order as they appear in
logs. Becauselogsis sorted, the matching entries form one contiguous run oflogs, and that run, in its original order, is the unique correct answer. Entries with equal timestamps keep their input order. - Return each matching entry unchanged, as the same
(timestamp, message)pair. Do not remove duplicates, even if two entries have the same timestamp and the same message. - If no entry falls in the range, return an empty list. This includes the cases where
start_timeis greater than the largest timestamp, whereend_timeis smaller than the smallest timestamp, and wherelogsis empty. - Do not modify
logs.
Constraints
0 <= len(logs) <= 10^50 <= timestamp <= 10^9for every entrylogs[i][0] <= logs[i + 1][0]for every validi0 <= start_time <= end_time <= 10^9- Each message is a string of 1 to 100 printable ASCII characters. Messages need not be distinct.
- Every timestamp and bound fits in a 32-bit signed integer.
Examples
Example 1
Input: logs = [(1, "boot"), (3, "connect"), (3, "retry"), (5, "ready"), (8, "shutdown")]
start_time = 3, end_time = 5
Output: [(3, "connect"), (3, "retry"), (5, "ready")]
Both entries at timestamp 3 are included, and the entry at 5 is included because the end bound is inclusive.
Example 2
Input: logs = [(2, "a"), (4, "b"), (6, "c")]
start_time = 7, end_time = 10
Output: []
start_time is greater than the largest timestamp, 6, so nothing matches.
Example 3
Input: logs = [(2, "a"), (2, "b"), (4, "c"), (6, "d")]
start_time = 0, end_time = 2
Output: [(2, "a"), (2, "b")]
The end bound equals the smallest timestamp, so both entries at timestamp 2 match.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.