Skip to content
mlmentorship

Sort starts to keep only one open union component

Preserve covered points with a sorted union frontier, then change touching policy or count discrete coverage.

Published · 8 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Sort starts to keep only one open union component

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list intervals of closed integer ranges [start, end], each with start <= end. Output. Return start-sorted, disjoint intervals whose union equals the union of all input ranges. Rules. Closed intervals sharing an endpoint overlap and must merge. Containment and repeated intervals do not add separate output ranges. The reference may reorder the input list; empty input returns []. Example. [[8, 10], [1, 3], [2, 6], [15, 18]] returns [[1, 6], [8, 10], [15, 18]]. For [[1, 2], [2, 3]], return [[1, 3]] because the ranges share point 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Sort ranges by start; compare each range with the last merged end, extending on overlap or appending on a gap.

Problem trace

Sorted order limits the next overlap to the final merged component

Worked example: extend the active endpoint before comparing the next intervalIntervals (1,4) and (2,6) merge to (1,6). The later (5,7) overlaps that updated endpoint, so all three merge to (1,7).Overlap extends the active endpoint;separated spans surviveSorted spans awaiting comparison[1,4][2,6][5,7]First merge extends active end to six[1,6][5,7]Pending five-to-seven overlapsupdated end six[1,7]Final union: [1,7]
Read it this way: Intervals (1,4) and (2,6) merge to (1,6). The later (5,7) overlaps that updated endpoint, so all three merge to (1,7). Would comparing the final start five against the obsolete end four preserve the correct union?
Full interview answer 8 min read

Combine overlapping closed intervals into disjoint ranges covering exactly the same points as the original intervals.

Problem

Input. A list intervals of closed integer ranges [start, end], each with start <= end.

Output. Return start-sorted, disjoint intervals whose union equals the union of all input ranges.

Rules. Closed intervals sharing an endpoint overlap and must merge. Containment and repeated intervals do not add separate output ranges. The reference may reorder the input list; empty input returns [].

Example. [[8, 10], [1, 3], [2, 6], [15, 18]] returns [[1, 6], [8, 10], [15, 18]]. For [[1, 2], [2, 3]], return [[1, 3]] because the ranges share point 2.

Picture

Sort to [1,3], [2,6], [8,10], [15,18]. The first two overlap, extending the open component to [1,6]. The gap before 8 closes that component permanently. Every future start is at least 8, so it cannot overlap that earlier [1,6]. The next gap similarly closes [8,10] before [15,18].

After each prefix, output components are ordered, disjoint and cover exactly the processed ranges. Only the last component remains eligible for extension.

Problem trace

Sorted order limits the next overlap to the final merged component

Input and goalMerge every pair of overlapping ranges.
Sort the concrete inputSort the four ranges by start. Only the final merged component can overlap the next range.
1: [1,3]
2: [2,6]
3: [8,10]
4: [15,18]
ordersorted by start
max
18
order
sorted by start
index 0
1: [1,3]

Recognize it
Use it when arbitrary ranges must be coalesced by overlap; sorting by start guarantees that any range able to overlap the current merged component appears before a later gap.
Keep true
Before each current interval, merged is sorted, disjoint, and exactly covers all processed ranges; only merged[-1] can overlap current because starts are nondecreasing.
Reuse it
Sorting can turn a global overlap problem into a local frontier check: preserve a completed prefix and keep only the final component open for possible extension.
Sort the four ranges by start. Only the final merged component can overlap the next range. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can the next sorted interval affect only the final merged component?
Reference drawing

Problem trace

Sorted order limits the next overlap to the final merged component

Worked example: extend the active endpoint before comparing the next intervalIntervals (1,4) and (2,6) merge to (1,6). The later (5,7) overlaps that updated endpoint, so all three merge to (1,7).Overlap extends the active endpoint;separated spans surviveSorted spans awaiting comparison[1,4][2,6][5,7]First merge extends active end to six[1,6][5,7]Pending five-to-seven overlapsupdated end six[1,7]Final union: [1,7]
Execution trace
Input and goalMerge every pair of overlapping ranges.
Sort the concrete inputSort the four ranges by start. Only the final merged component can overlap the next range.
1: [1,3]
2: [2,6]
3: [8,10]
4: [15,18]
ordersorted by start
max
18
order
sorted by start
index 0
1: [1,3]

Recognize it
Use it when arbitrary ranges must be coalesced by overlap; sorting by start guarantees that any range able to overlap the current merged component appears before a later gap.
Keep true
Before each current interval, merged is sorted, disjoint, and exactly covers all processed ranges; only merged[-1] can overlap current because starts are nondecreasing.
Reuse it
Sorting can turn a global overlap problem into a local frontier check: preserve a completed prefix and keep only the final component open for possible extension.
Sort the four ranges by start. Only the final merged component can overlap the next range. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can the next sorted interval affect only the final merged component?
Read it this way: Intervals (1,4) and (2,6) merge to (1,6). The later (5,7) overlaps that updated endpoint, so all three merge to (1,7). Would comparing the final start five against the obsolete end four preserve the correct union?

On overlap, retain the larger end. For [1,10] followed by [2,3], replacing the end with 3 would lose covered points. On a gap, append a fresh component.

Code

def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
   if not intervals:
      return []

   ordered = sorted(intervals)
   merged = [ordered[0].copy()]

   for start, end in ordered[1:]:
      if start <= merged[-1][1]:
         merged[-1][1] = max(merged[-1][1], end)
      else:
         merged.append([start, end])
   return merged

sorted preserves input order and rows; the copied first row prevents later frontier updates from mutating an input row. Every returned row is newly allocated. Empty input returns [].

Sorting takes time. Answer storage is ; sorted lists, slicing and sorting workspace also take space. This is union, not maximum compatible selection or peak simultaneous resource demand.

Change the Touching Policy

New task: Coalesce only positive-width overlaps, leaving merely touching ranges separate.

Picture and change: Use strict start < last_end and require positive-width inputs. This changes grouping policy, not necessarily the covered real set.

def merge_strict_overlaps(intervals):
   merged = []
   for start, end in sorted(intervals):
      if merged and start < merged[-1][1]:
         merged[-1][1] = max(merged[-1][1], end)
      else:
         merged.append([start, end])
   return merged

Check: [[1,2],[2,3],[2,4]] returns [[1,2],[2,4]]. The first range only touches the second group; the equal-start ranges have positive-width overlap and merge. Neither endpoint policy should be silently imported from a scheduling task.

Use when: Shared endpoints alone must not coalesce groups.

Change to Integer Coverage

New task: Count distinct integer coordinates covered by closed integer ranges.

Picture and change: First obtain disjoint union components. Each contributes end-start+1 integer points without enumerating them.

def covered_integer_points(intervals):
   return sum(end - start + 1
            for start, end in merge_intervals(intervals))

Check: [[1,3],[2,6],[8,10]] covers six points 1..6 and three points 8..10: total 9. Continuous length would omit the +1 and answer a different question. Both adaptations retain the sorting bound and fresh union rows.

Use when: Union representation becomes a discrete coverage count.

Transfer Check

Why cannot earliest-finish scheduling replace this scan?

Answer

Scheduling discards overlapping ranges to maximize a compatible subset. Union must preserve every covered point, so it extends components instead of rejecting their coverage.