You are given an unsorted list of timestamps, each written as YYYY-MM-DD-HH-MM. Report the calendar dates they cover as intervals: every maximal run of consecutive days on which at least one timestamp falls becomes one interval, given by its first and last date as YYYY-MM-DD. The interviewer did not allow sorting and asked for a linear-time solution.
Function Signature
def covered_date_intervals(timestamps: list[str]) -> list[list[str]]:
Rules
-
A timestamp's date is its
YYYY-MM-DD
part; the hour and minute are ignored. A date is covered when at least one timestamp falls on it. Several timestamps on one date, including exact duplicates, count once.
-
Two dates are consecutive when the second is the next calendar day after the first in the Gregorian calendar, across month and year boundaries and including February 29 in leap years.
-
Return one
[start, end]
pair for each maximal run of consecutive covered dates, both as
YYYY-MM-DD
strings with
start <= end
. A covered date with no covered neighbor gives
[d, d]
. Every covered date lies in exactly one interval, and no two intervals overlap or touch.
-
The intervals may be returned in any order; the result is compared as a set of intervals. An empty input returns
[]
.
-
The expected solution runs in O(n) expected time for
n
timestamps and does not sort the timestamps or their dates.
Constraints
-
0 <= n <= 10^5
, where
n = len(timestamps)
-
Every timestamp is a valid, zero-padded date and 24-hour time with a year between 1900 and 2100.
-
Timestamps are in no particular order and may repeat.
Examples
Example 1
Input: timestamps = ["2024-03-02-09-15", "2024-02-28-23-59", "2024-03-05-08-00",
"2024-03-01-00-05", "2024-02-29-12-00", "2024-03-02-18-30"]
Output: [["2024-02-28", "2024-03-02"], ["2024-03-05", "2024-03-05"]]
2024 is a leap year, so February 28, February 29, March 1 and March 2 form one run, and the two timestamps on March 2 count once. March 3 and March 4 have no timestamp, so March 5 stands alone. The two intervals may come back in either order.
Example 2
Input: timestamps = ["2024-01-01-01-00", "2023-12-30-10-10", "2023-12-31-22-00"]
Output: [["2023-12-30", "2024-01-01"]]
The run crosses a year boundary.
Example 3
Input: timestamps = ["2023-03-01-10-00", "2023-03-03-07-45", "2023-02-28-23-00"]
Output: [["2023-02-28", "2023-03-01"], ["2023-03-03", "2023-03-03"]]
2023 is not a leap year, so March 1 directly follows February 28. March 2 is not covered, so March 3 forms its own interval.