MediumArrayTwo PointersIntervals

1 approach, code in every language

Problem description

You are handed two lists of closed intervals, each list individually sorted by start value and internally free of overlaps. Compute the intersection of the two lists: every span that lies inside an interval from the first list and simultaneously inside an interval from the second list.

Return these overlapping spans as a sorted list of closed intervals. A shared single point counts as a valid intersection.

Example 1

Input: firstList = [[0,2],[5,10]], secondList = [[1,5],[8,12]]

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

0-2 meets 1-5 at 1-2, 5-10 meets 1-5 at the single point 5, and 5-10 meets 8-12 at 8-10.

Example 2

Input: firstList = [[1,4]], secondList = [[5,7]]

Output: []

The only interval in each list sits entirely apart from the other, so there is no overlap.

Constraints

  • 0 ≤ firstList.length, secondList.length ≤ 1000
  • firstList.length + secondList.length ≥ 1
  • 0 ≤ start ≤ end ≤ 10^9
  • Each list is sorted by start and contains no overlapping intervals

After the pattern

Now solve one you haven't seen.

Shared Observation Windows is our own problem on the technique behind Interval List Intersections: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free