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.
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.
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]Constraints
0 ≤ firstList.length, secondList.length ≤ 1000firstList.length + secondList.length ≥ 10 ≤ 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.
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
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 resultfunction intervalIntersection(A: number[][], B: number[][]): number[][] {
const result: number[][] = [];
let i = 0, j = 0;
while (i < A.length && j < B.length) {
const lo = Math.max(A[i][0], B[j][0]);
const hi = Math.min(A[i][1], B[j][1]);
if (lo <= hi) result.push([lo, hi]);
if (A[i][1] < B[j][1]) i++;
else j++;
}
return result;
}Complexity
| Metric | Value | Reason |
|---|---|---|
| Time | O(m + n) | Each pointer advances at most m or n times |
| Space | O(m + n) | Output size in the worst case |
Edge Case Thinking
| Scenario | Handling |
|---|---|
| Either list empty | Return [] — no intersection possible. |
Point intersection [5,5] | Valid! lo = hi = 5, and 5 ≤ 5 is true. |
| No overlap anywhere | lo > hi on every iteration; result stays empty. |
| One list fully inside the other | Two pointers still handle it — just different advance patterns. |
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.