Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 1 Updated

Interval List Intersections

Two pointers; advance the one whose interval ends first.

  • Full 5m
  • Revision 2m
  • Flow 1m

Problem Statement

Given two lists of closed, sorted, disjoint intervals, return their intersection — every range that appears in both lists.

Input

Two arrays of intervals, each already sorted and pairwise disjoint.

Example input
firstList  = [[0,2],[5,10],[13,23],[24,25]]
secondList = [[1,5],[8,12],[15,24],[25,26]]

Output

A sorted list of the intersecting intervals.

Expected output
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]

Constraints

  • 0 ≤ firstList.length, secondList.length ≤ 1000
  • firstList.length + secondList.length ≥ 1
  • 0 ≤ startᵢ < endᵢ ≤ 10⁹
  • Each input list is already sorted and contains disjoint intervals.

Intuition

Two pointers — one per list. At each step compute the candidate intersection using [max(starts), min(ends)]. If lo ≤ hi, add it. Then advance the pointer whose interval ends first — it can’t intersect anything else from the other list.

Why advance the smaller-end pointer
  A:  [──────]      ← ends earliest, can't match more B's
  B:     [──────────]
         ▓▓▓         ← intersection = [max(starts), min(ends)]
 
  After recording, A moves forward; B still has room to match new A's.

Solution

interval_intersections.py
def intervalIntersection(A: list, B: list) -> list:
    result = []
    i = j = 0
 
    while i < len(A) and j < len(B):
        lo = max(A[i][0], B[j][0])
        hi = min(A[i][1], B[j][1])
 
        if lo <= hi:
            result.append([lo, hi])
 
        # Advance the pointer with the smaller end
        if A[i][1] < B[j][1]:
            i += 1
        else:
            j += 1
 
    return result

Complexity

MetricValueReason
TimeO(m + n)Each pointer advances at most m or n times
SpaceO(m + n)Output size in the worst case

Edge Case Thinking

ScenarioHandling
Either list emptyReturn [] — no intersection possible.
Point intersection [5,5]Valid! lo = hi = 5, and 5 ≤ 5 is true.
No overlap anywherelo > hi on every iteration; result stays empty.
One list fully inside the otherTwo pointers still handle it — just different advance patterns.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.