KatInterview

Merge Overlapping Regions from Two Sorted Interval Lists

Greedy & IntervalsAuto-graded · 24 test cases
MediumAuto-gradedGreedy & Intervalsintervalstwo-pointerssorting

Last updated

Tests two-pointer traversal on sorted interval lists to find all pairwise overlaps in linear time.

You are given two lists of closed intervals. Each list is sorted by starting position, and no two intervals within the same list overlap or touch each other. Your task is to find every region where an interval from the first list overlaps with an interval from the second list.

Two closed intervals overlap if they share at least one point. For example, [1, 3] and [3, 5] overlap at the single point 3, producing the intersection [3, 3].

Return all such overlapping regions as a list of intervals, sorted by starting position.

Constraints

  • Each input list contains between 0 and 200,000 intervals
  • Each interval is represented as [start, end] where start <= end
  • All endpoint values are integers in the range [-10^9, 10^9]
  • Within each input list, intervals are sorted and pairwise disjoint (no overlap or touching)
  • Your solution must run in O(m + n) time where m and n are the lengths of the two lists

Examples

Example 1

Input: find_interval_overlaps([[0, 2], [5, 10], [13, 23], [24, 25]], [[1, 5], [8, 12], [15, 24], [25, 26]])

Output: [[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]]

Example 2

Input: find_interval_overlaps([], [[1, 2]])

Output: []

Example 3

Input: find_interval_overlaps([[1, 2]], [])

Output: []

Example 4

Input: find_interval_overlaps([[0, 10]], [[1, 2], [4, 5], [8, 12]])

Output: [[1, 2], [4, 5], [8, 10]]

Hints

Hint 1

Use two pointers, one for each list, and examine pairs of intervals without backtracking.

Hint 2

When two intervals overlap, compute the intersection using max of starts and min of ends. Remember that closed intervals touching at a single point still count as overlapping.

Hint 3

After recording an intersection, advance the pointer pointing to whichever interval ends first—it cannot possibly intersect anything further in the other list.