Problem
LeetCode #986 — one-liner.
- Given two sorted, disjoint interval lists, return the list of all their pairwise intersections.
Key insight
Two pointers, advance the earlier end.
- Both lists are already sorted and disjoint — no need to re-sort.
- At each step compute the candidate intersection
[max(starts), min(ends)]; iflo ≤ hi, it’s a real intersection. - Advance the pointer whose interval ends first — the other list can still yield more intersections with the current interval.
Solution template
One while-loop.
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])
if A[i][1] < B[j][1]: i += 1
else: j += 1Complexity
Linear in total size.
- Time
O(m + n)— each pointer advances at mostmorntimes. - Space
O(m + n)— worst-case output size.
Edge cases
Three to remember.
- Either list empty → return
[]. - Point intersection
[5, 5]— valid becauselo = hi = 5and5 ≤ 5. - No overlap anywhere →
lo > hievery step → result stays empty.
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.