Longest-Running Timeline Tags After Overwrites
Easy · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A scheduler records sequential configuration windows along a timeline. Each entry (start, end, label) assigns the string label to the half-open interval [start, end) (start included, end excluded).
Entries take effect in arrival order. Whenever a newly recorded window [start, end) overlaps one or more existing windows on the timeline, the newer entry overwrites the shared region—older windows may be completely erased, shortened at either boundary, or split into two separate fragments.
Implement:
def top_k_interval_labels(intervals: List[Tuple[int, int, str]], k: int) -> List[str]:
After replaying every entry in intervals:
- Sum the total surviving length across all remaining fragments for each distinct
label. - Discard any
labelwhose surviving total length is0. - Rank the remaining labels from largest total length to smallest, breaking ties in ascending ASCII lexicographical order (for example,
'B' < 'a' < 'b'). - Return the first
klabels in this ranking (or every surviving label in ranked order when fewer thanklabels retain positive length).
Examples
Example 1
Input:
intervals = [(0, 12, "web"), (3, 9, "jobs"), (5, 10, "api")]
k = 2
Output: ["api", "web"]
(0, 12, "web")claims[0, 12).(3, 9, "jobs")overwrites the middle, splitting"web"into[0, 3)and[9, 12)while claiming[3, 9).(5, 10, "api")trims[3, 9)"jobs"down to[3, 5)(length2), trims[9, 12)"web"down to[10, 12)(length2), leaves[0, 3)"web"intact (length3), and claims[5, 10)(length5).
Surviving totals are "api": 5, "web": 3 + 2 = 5, and "jobs": 2. Because "api" precedes "web" in ASCII order on the tie at 5, the top 2 labels are ["api", "web"].
Example 2
Input:
intervals = [(2, 7, "init"), (1, 9, "main")]
k = 3
Output: ["main"]
(1, 9, "main") completely covers [2, 7), reducing "init" to 0 surviving length and giving "main" length 8. Zero-length labels are excluded, and since fewer than 3 positive-length labels remain, all surviving labels are returned: ["main"].
Constraints
0 <= len(intervals) <= 20000 <= start < end <= 10^91 <= len(label) <= 30, consisting of uppercase and lowercase ASCII letters1 <= k <= 1000
Step-by-step walkthrough
Understand the timeline painting model
Picture the timeline as a long ruler where opaque strips of labeled tape
[start, end)are laid down one after another. Each strip carries a stringlabel, and whenever a newer strip overlaps an older strip, the newer strip covers up the overlapping region underneath it:Example 1: 1) Add (0, 12, "web"): [0 =================== web =================== 12) 2) Add (3, 9, "jobs"): [0 == web == 3)[3 ===== jobs ===== 9)[9 = web = 12) 3) Add (5, 10, "api"): [0 == web == 3)[3=jobs=5)[5 === api === 10)[10=web=12)Once every strip has been placed, we sum the visible length belonging to each label (
api: 5,web: 3 + 2 = 5,jobs: 2) and return up toklabels:- Primary sort: largest surviving total length first.
- Tie-breaker: ascending ASCII string comparison (
'a'before'b', and uppercase letters precede lowercase so'B' < 'a' < 'b'). - Zero-length rule: any label that was completely covered has
0visible length and must not appear in the output.
Why painting individual time units fails
On tiny numbers, you could store a dictionary
owner[t] = labelfor every integer unittinrange(start, end), overwriteowner[t]as entries arrive, and count how many units each label owns at the end.That works as a brute-force check on tiny ranges, but check the input bounds:
- Up to
n = 2000entries. - Coordinates up to
10^9!
A single entry
(0, 10^9, "base")spans one billion unit cells — stepping across10^9coordinates immediately exhausts both time and memory. Instead, our runtime must scale with the count of intervals (2000), never with their coordinate span.- Up to
Key idea: maintain disjoint segments and clip on arrival
Instead of tracking unit coordinates, represent the visible timeline as a list of non-overlapping segments
(seg_start, seg_end, seg_label).Whenever a new entry
[new_start, new_end)arrives, compare it against every existing segment[seg_start, seg_end):New interval: new_start ============== new_end 1) Disjoint (left or right): [seg] or [seg] seg_end <= new_start OR seg_start >= new_end --> keep (seg_start, seg_end) unchanged 2) Completely covered: [==== seg ====) seg_start >= new_start AND seg_end <= new_end --> drop completely! 3) Clipped on one side: [=== left ===|xxxxxx) or (xxxxxx|=== right ===) keep (seg_start, new_start) if seg_start < new_start keep (new_end, seg_end) if seg_end > new_end 4) Split down the middle: [=== left ===|xxxxxxxxxxxxxx|=== right ===) BOTH conditions hold! 1 old segment becomes 2 surviving remnants.After checking all existing segments, append
(new_start, new_end, new_label).Could repeated splits cause the segment list to double at every step and grow exponentially? No! To split an existing segment into two remnants (Case 4),
[new_start, new_end)must both start and end strictly inside that single segment. Because existing segments are mutually disjoint, a new interval can sit strictly inside at most one old segment! Eachapply_overridecall therefore adds at most2net segments (at most+1from a split, plus+1for the new interval), keeping the list strictly under2nsegments (< 4000forn = 2000).Code the single-interval override helper
Pay attention to two boundary comparisons in
apply_overridethat prevent subtle bugs:- Touching endpoints (
<=and>=): Because intervals are half-open,[0, 5)and[5, 8)share zero points, soseg_end <= new_starttreats them as non-overlapping. - Strict inequalities (
<and>) for remnants: Checkingseg_start < new_startandseg_end > new_endguarantees every surviving fragment has strictly positive length (> 0). Zero-length ghost fragments like(2, 2, "init")are never emitted, so erased labels never sneak into the output!
from typing import Any, Dict, List, Optional, Set, Tuple def apply_override( timeline: List[Tuple[int, int, str]], new_start: int, new_end: int, new_label: str, ) -> List[Tuple[int, int, str]]: """Return an updated disjoint timeline where [new_start, new_end) is owned by new_label.""" updated_timeline = [] for seg_start, seg_end, seg_label in timeline: # Half-open intervals [seg_start, seg_end) and [new_start, new_end) do not overlap # when one ends at or before the other starts (<= and >= handle touching endpoints). if seg_end <= new_start or seg_start >= new_end: updated_timeline.append((seg_start, seg_end, seg_label)) continue # Overlapping case: [new_start, new_end) paints over the middle/shared part. # Keep any strictly positive left remnant [seg_start, new_start) before new_start. if seg_start < new_start: updated_timeline.append((seg_start, new_start, seg_label)) # Keep any strictly positive right remnant [new_end, seg_end) after new_end. # When both conditions hold, the old piece is split into two separate segments. if seg_end > new_end: updated_timeline.append((new_end, seg_end, seg_label)) # Finally add the new interval itself, which now owns all of [new_start, new_end). updated_timeline.append((new_start, new_end, new_label)) return updated_timeline- Touching endpoints (
Sum durations per label and rank the top k
Notice we never need to sort
timelineby coordinate: because all segments intimelineare mutually disjoint and have positive length, summingseg_end - seg_startper label in adurationsdictionary yields each surviving label's exact total length, while erased labels never enterdurationsat all.To rank labels by descending duration and ascending ASCII order simultaneously, build
(-total_duration, label)tuples and call.sort():- Larger durations become more negative (
-8 < -5), sorting higher durations first. - Tied durations share the same
-total_duration, so Python compares the second elementlabelin ascending ASCII order ("api" < "web"). - Slicing
ranked_pairs[:k]cleanly returns every surviving label when fewer thankremain (as in Example 2).
def top_k_interval_labels(intervals: List[Tuple[int, int, str]], k: int) -> List[str]: # Phase 1: Replay assignments in arrival order. # timeline: list of mutually disjoint (start, end, label) segments with start < end, e.g. [(0, 3, 'web')]. timeline: List[Tuple[int, int, str]] = [] for start, end, label in intervals: timeline = apply_override(timeline, start, end, label) # Phase 2: Sum total surviving duration for each label across all disjoint segments. # durations: maps label -> positive total active duration, e.g. {'web': 5, 'api': 5, 'jobs': 2}. durations: Dict[str, int] = {} for seg_start, seg_end, label in timeline: segment_length = seg_end - seg_start durations[label] = durations.get(label, 0) + segment_length # Phase 3: Sort labels by highest duration first, breaking ties alphabetically (ASCII order). # Negating duration lets Python's ascending tuple sort order larger durations first while keeping label ascending. ranked_pairs = [] for label, total_duration in durations.items(): ranked_pairs.append((-total_duration, label)) ranked_pairs.sort() # Extract up to k winning labels (slicing [:k] safely returns all items if len(ranked_pairs) < k). top_labels = [] for neg_duration, label in ranked_pairs[:k]: top_labels.append(label) return top_labels- Larger durations become more negative (
Trace Example 1 step by step
Let's trace
intervals = [(0, 12, "web"), (3, 9, "jobs"), (5, 10, "api")],k = 2:Start: timeline = [] Step 1 — apply (0, 12, "web"): timeline = [(0, 12, "web")] Step 2 — apply (3, 9, "jobs"): - (0, 12, "web") overlaps [3, 9): 0 < 3 -> keep left remnant (0, 3, "web") 12 > 9 -> keep right remnant (9, 12, "web") - append (3, 9, "jobs") timeline = [(0, 3, "web"), (9, 12, "web"), (3, 9, "jobs")] Step 3 — apply (5, 10, "api"): - (0, 3, "web") has 3 <= 5 (disjoint) -> keep (0, 3, "web") - (9, 12, "web") overlaps [5, 10): 9 < 5 is False; 12 > 10 -> keep (10, 12, "web") - (3, 9, "jobs") overlaps [5, 10): 3 < 5 -> keep (3, 5, "jobs"); 9 > 10 is False - append (5, 10, "api") timeline = [(0, 3, "web"), (10, 12, "web"), (3, 5, "jobs"), (5, 10, "api")] Sum durations: durations = {"web": 3 + 2 = 5, "jobs": 2, "api": 5} ranked_pairs = [(-5, "api"), (-5, "web"), (-2, "jobs")] top 2 labels = ["api", "web"]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def apply_override( timeline: List[Tuple[int, int, str]], new_start: int, new_end: int, new_label: str, ) -> List[Tuple[int, int, str]]: """Return an updated disjoint timeline where [new_start, new_end) is owned by new_label.""" updated_timeline = [] for seg_start, seg_end, seg_label in timeline: # Half-open intervals [seg_start, seg_end) and [new_start, new_end) do not overlap # when one ends at or before the other starts (<= and >= handle touching endpoints). if seg_end <= new_start or seg_start >= new_end: updated_timeline.append((seg_start, seg_end, seg_label)) continue # Overlapping case: [new_start, new_end) paints over the middle/shared part. # Keep any strictly positive left remnant [seg_start, new_start) before new_start. if seg_start < new_start: updated_timeline.append((seg_start, new_start, seg_label)) # Keep any strictly positive right remnant [new_end, seg_end) after new_end. # When both conditions hold, the old piece is split into two separate segments. if seg_end > new_end: updated_timeline.append((new_end, seg_end, seg_label)) # Finally add the new interval itself, which now owns all of [new_start, new_end). updated_timeline.append((new_start, new_end, new_label)) return updated_timeline def top_k_interval_labels(intervals: List[Tuple[int, int, str]], k: int) -> List[str]: # Phase 1: Replay assignments in arrival order. # timeline: list of mutually disjoint (start, end, label) segments with start < end, e.g. [(0, 3, 'web')]. timeline: List[Tuple[int, int, str]] = [] for start, end, label in intervals: timeline = apply_override(timeline, start, end, label) # Phase 2: Sum total surviving duration for each label across all disjoint segments. # durations: maps label -> positive total active duration, e.g. {'web': 5, 'api': 5, 'jobs': 2}. durations: Dict[str, int] = {} for seg_start, seg_end, label in timeline: segment_length = seg_end - seg_start durations[label] = durations.get(label, 0) + segment_length # Phase 3: Sort labels by highest duration first, breaking ties alphabetically (ASCII order). # Negating duration lets Python's ascending tuple sort order larger durations first while keeping label ascending. ranked_pairs = [] for label, total_duration in durations.items(): ranked_pairs.append((-total_duration, label)) ranked_pairs.sort() # Extract up to k winning labels (slicing [:k] safely returns all items if len(ranked_pairs) < k). top_labels = [] for neg_duration, label in ranked_pairs[:k]: top_labels.append(label) return top_labels✅ Submit now — all tests should pass.
Intuition & how it works
Imagine laying opaque strips of labeled masking tape onto a long ruler one after another. Whenever a new strip lands on top of an older strip, it hides the covered portion — erasing the old strip completely, trimming one of its ends, or slicing it into a left piece and a right piece. Once all strips are placed, we add up how many visible units belong to each label and pick the top k.
Recording every integer unit in an array fails because one interval [0, 10^9) spans a billion coordinates, exhausting memory and time immediately. Summing input lengths without replaying overwrites also fails because covered regions would still be credited to earlier labels.
Instead, we represent the visible ruler as a list of disjoint half-open intervals — ranges [start, end) that include start and exclude end — and clip existing fragments whenever a new interval arrives. Because a new interval can start and end strictly inside at most one existing disjoint fragment, each update increases the fragment count by at most two, keeping the list under 2n fragments (< 4,000 for n = 2,000). Finally, we sort (-duration, label) pairs so ties break in lexicographical order (character-by-character comparison by ASCII code, where 'a' < 'b' and 'B' < 'a').
On Example 1 ((0, 12, "web"), (3, 9, "jobs"), (5, 10, "api"), k = 2):
(0, 12, "web")creates[(0, 12, "web")].(3, 9, "jobs")splits"web"into(0, 3)and(9, 12)and adds(3, 9, "jobs").(5, 10, "api")leaves(0, 3, "web")intact, trims(9, 12, "web")to(10, 12, "web"), trims(3, 9, "jobs")to(3, 5, "jobs"), and adds(5, 10, "api").- Summing gives
api = 5,web = 3 + 2 = 5,jobs = 2; sorting[(-5, "api"), (-5, "web"), (-2, "jobs")]and taking the first2yields["api", "web"].
Complexity
Let n be the number of input intervals (n <= 2000) and L be the number of unique surviving labels (L <= n).
- Time:
O(n^2 + L log L). Afteriarrivals,timelineholds at most2i - 1disjoint fragments because each arrival splits at most one existing fragment in two and appends itself. Scanningtimelineacross allnarrivals performs at most1 + 3 + 5 + ... + (2n - 1) = n^2fragment checks (at most4,000,000simple comparisons whenn = 2000), and sorting theLlabel totals takesO(L log L)time. - Space:
O(n).timelineholds fewer than2ntuples, whiledurationsandranked_pairsstore at mostL <= nentries.
Edge cases
- Empty
intervalslist:timelinestays empty and the function returns[]. klarger than the surviving label count (Example 2): Python sliceranked_pairs[:k]returns all surviving labels in ranked order without raising an index error.- Completely overwritten labels (Example 2): Zero fragments survive for
"init", so it never entersdurationsand never appears with0duration. - Middle overwrite splitting a fragment in two: Both
seg_start < new_startandseg_end > new_endhold, preserving both left and right remnants. - One wide overwrite spanning several fragments: Interior fragments disappear completely while the two boundary fragments are trimmed cleanly.
- Touching half-open intervals (e.g.
[0, 5)and[5, 10)):seg_end <= new_start(5 <= 5) recognizes they share zero points and leaves both untouched. - Disconnected fragments with the same label:
durations[label]sums lengths across all surviving fragments oflabel. - Mixed uppercase and lowercase ties: Standard ASCII string comparison orders
'B' < 'a' < 'b'.
Common mistakes
- Losing the right remnant on a split. Writing
elif seg_end > new_end:instead of a separateif seg_end > new_end:drops the right remnant whenever a new interval falls strictly inside an older one. - Off-by-one boundary cuts (
new_start - 1ornew_end + 1). With half-open intervals[seg_start, seg_end), removing[new_start, new_end)leaves[seg_start, new_start)and[new_end, seg_end)directly; closed-interval offsets drop 1 unit of length at each cut. - Emitting zero-length remnants (
<=instead of<). Keeping(seg_start, new_start)whenseg_start == new_startcreates zero-length(start, start, label)entries that keep erased labels alive with0total duration. - Sorting
(duration, label)withreverse=True. Reversing the entire tuple puts larger durations first, but also reverses alphabetical tie-breaking ("web"before"api"). Negating the numeric duration(-total_duration, label)sorts durations descending while keeping labels ascending. - Simulating individual unit cells. Coordinates up to
10^9make per-unit loops time out.
Alternative approaches
- Offline reverse painting with coordinate compression (
O(n log n)): Coordinate compression gathers all<= 2ndistinct start/end coordinates and sorts them so adjacent coordinates define<= 2n - 1elementary blocks. Scanningintervalsbackwards from last to first, each block's final owner is the first interval (from the back) that covers it; using a "next unpainted block" jump pointer (Disjoint Set Union) paints every block at most once inO(n log n)total time. - Sorted segment list with binary search: Maintaining
timelinesorted byseg_startand usingbisectlocates the overlapped slice inO(log n)comparisons and replaces only that slice.
Follow-up questions
- How would you redesign the data structure to ingest 100,000 live range updates and serve top-k queries on a continuous stream? At
n = 10^5, rescanning a flat list per update would takeO(n^2) = 10^10steps. Instead, maintain the disjoint fragments ordered bystartin a balanced binary search tree (BST) — a self-balancing sorted map (such as Java'sTreeMapor Python'ssortedcontainers.SortedDict) supporting predecessor search, insertion, and deletion inO(log n)time. On each[new_start, new_end, new_label)arrival, seek to the fragment at or immediately beforenew_start, walk forward trimming or deleting only overlapping fragments while adjustingdurations[label], and mirror each label's updated(-duration, label)key in a second balanced BST so updates take amortizedO(log n)time and top-kreads takeO(k)time by iterating the firstknodes. - Between an interval tree, a lazy segment tree, and a key-ordered balanced BST, which structures achieve O(n log n) offline or online maintenance here and why? Both a key-ordered balanced BST (online or offline) and a lazy segment tree with coordinate compression (offline) achieve
O(n log n), whereas an interval tree — a specialized tree designed to index mutually overlapping intervals for stab queries — adds unnecessary complexity because our active fragments are always mutually disjoint! In a plain balanced BST keyed byseg_start, each update creates at most 3 fragments (left remnant, right remnant, and the new interval), and every deleted fragment must have been inserted earlier, bounding total insertions and deletions acrossnupdates to<= 3natO(log n)each (O(n log n)overall). A lazy segment tree (a binary tree over elementary intervals that pushes range-overwrite tags down on demand inO(log n)time) matchesO(n log n)offline once all<= 2nendpoints are compressed, orO(n log C)(C = 10^9) online via dynamic node allocation. - How would you adapt your design to answer top-k duration queries restricted to an arbitrary sub-window [q_start, q_end)? Keep the active timeline sorted by
seg_start(either in a sorted array or balanced BST), and at query time intersect overlapping fragments[seg_start, seg_end)against[q_start, q_end)viamin(seg_end, q_end) - max(seg_start, q_start). Binary search jumps straight to the first fragment withseg_end > q_startand stops as soon asseg_start >= q_end, accumulating totals only inside[q_start, q_end)inO(log n + W + L_w log L_w)time, whereWis the number of fragments intersecting the window andL_wis the count of distinct labels among them.
python
def top_k_in_window(timeline, q_start, q_end, k):
durations = {}
for seg_start, seg_end, label in timeline:
clipped_start = max(seg_start, q_start)
clipped_end = min(seg_end, q_end)
if clipped_end > clipped_start:
durations[label] = durations.get(label, 0) + (clipped_end - clipped_start)
ranked = sorted((-dur, lbl) for lbl, dur in durations.items())
return [lbl for _, lbl in ranked[:k]]
Follow-up questions
- How would you redesign the data structure to ingest 100,000 live range updates and serve top-k queries on a continuous stream?
- Between an interval tree, a lazy segment tree, and a key-ordered balanced BST, which structures achieve O(n log n) offline or online maintenance here and why?
- How would you adapt your design to answer top-k duration queries restricted to an arbitrary sub-window [q_start, q_end)?
Similar questions
- Hourly Window Billing With Rate Overrides
- Design a Real-Time Workspace Chat Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance