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:

  1. Sum the total surviving length across all remaining fragments for each distinct label.
  2. Discard any label whose surviving total length is 0.
  3. Rank the remaining labels from largest total length to smallest, breaking ties in ascending ASCII lexicographical order (for example, 'B' < 'a' < 'b').
  4. Return the first k labels in this ranking (or every surviving label in ranked order when fewer than k labels 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) (length 2), trims [9, 12) "web" down to [10, 12) (length 2), leaves [0, 3) "web" intact (length 3), and claims [5, 10) (length 5).

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) <= 2000
  • 0 <= start < end <= 10^9
  • 1 <= len(label) <= 30, consisting of uppercase and lowercase ASCII letters
  • 1 <= k <= 1000

Step-by-step walkthrough

  1. 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 string label, 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 to k labels:

    • 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 0 visible length and must not appear in the output.
  2. Why painting individual time units fails

    On tiny numbers, you could store a dictionary owner[t] = label for every integer unit t in range(start, end), overwrite owner[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 = 2000 entries.
    • Coordinates up to 10^9!

    A single entry (0, 10^9, "base") spans one billion unit cells — stepping across 10^9 coordinates immediately exhausts both time and memory. Instead, our runtime must scale with the count of intervals (2000), never with their coordinate span.

  3. 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! Each apply_override call therefore adds at most 2 net segments (at most +1 from a split, plus +1 for the new interval), keeping the list strictly under 2n segments (< 4000 for n = 2000).

  4. Code the single-interval override helper

    Pay attention to two boundary comparisons in apply_override that prevent subtle bugs:

    • Touching endpoints (<= and >=): Because intervals are half-open, [0, 5) and [5, 8) share zero points, so seg_end <= new_start treats them as non-overlapping.
    • Strict inequalities (< and >) for remnants: Checking seg_start < new_start and seg_end > new_end guarantees 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
    
  5. Sum durations per label and rank the top k

    Notice we never need to sort timeline by coordinate: because all segments in timeline are mutually disjoint and have positive length, summing seg_end - seg_start per label in a durations dictionary yields each surviving label's exact total length, while erased labels never enter durations at 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 element label in ascending ASCII order ("api" < "web").
    • Slicing ranked_pairs[:k] cleanly returns every surviving label when fewer than k remain (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
    
  6. 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"]
    
  7. 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):

  1. (0, 12, "web") creates [(0, 12, "web")].
  2. (3, 9, "jobs") splits "web" into (0, 3) and (9, 12) and adds (3, 9, "jobs").
  3. (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").
  4. Summing gives api = 5, web = 3 + 2 = 5, jobs = 2; sorting [(-5, "api"), (-5, "web"), (-2, "jobs")] and taking the first 2 yields ["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). After i arrivals, timeline holds at most 2i - 1 disjoint fragments because each arrival splits at most one existing fragment in two and appends itself. Scanning timeline across all n arrivals performs at most 1 + 3 + 5 + ... + (2n - 1) = n^2 fragment checks (at most 4,000,000 simple comparisons when n = 2000), and sorting the L label totals takes O(L log L) time.
  • Space: O(n). timeline holds fewer than 2n tuples, while durations and ranked_pairs store at most L <= n entries.

Edge cases

  • Empty intervals list: timeline stays empty and the function returns [].
  • k larger than the surviving label count (Example 2): Python slice ranked_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 enters durations and never appears with 0 duration.
  • Middle overwrite splitting a fragment in two: Both seg_start < new_start and seg_end > new_end hold, 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 of label.
  • 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 separate if 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 - 1 or new_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) when seg_start == new_start creates zero-length (start, start, label) entries that keep erased labels alive with 0 total duration.
  • Sorting (duration, label) with reverse=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^9 make per-unit loops time out.

Alternative approaches

  • Offline reverse painting with coordinate compression (O(n log n)): Coordinate compression gathers all <= 2n distinct start/end coordinates and sorts them so adjacent coordinates define <= 2n - 1 elementary blocks. Scanning intervals backwards 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 in O(n log n) total time.
  • Sorted segment list with binary search: Maintaining timeline sorted by seg_start and using bisect locates the overlapped slice in O(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 take O(n^2) = 10^10 steps. Instead, maintain the disjoint fragments ordered by start in a balanced binary search tree (BST) — a self-balancing sorted map (such as Java's TreeMap or Python's sortedcontainers.SortedDict) supporting predecessor search, insertion, and deletion in O(log n) time. On each [new_start, new_end, new_label) arrival, seek to the fragment at or immediately before new_start, walk forward trimming or deleting only overlapping fragments while adjusting durations[label], and mirror each label's updated (-duration, label) key in a second balanced BST so updates take amortized O(log n) time and top-k reads take O(k) time by iterating the first k nodes.
  • 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 by seg_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 across n updates to <= 3n at O(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 in O(log n) time) matches O(n log n) offline once all <= 2n endpoints are compressed, or O(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) via min(seg_end, q_end) - max(seg_start, q_start). Binary search jumps straight to the first fragment with seg_end > q_start and stops as soon as seg_start >= q_end, accumulating totals only inside [q_start, q_end) in O(log n + W + L_w log L_w) time, where W is the number of fragments intersecting the window and L_w is 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

Similar questions

More Crusoe interview questions

All 3 Crusoe questions →