#986
Interval List Intersections
MediumArrayTwo PointersSweep LineTwo PointersSweep Line
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses two pointers to traverse both lists simultaneously. This is efficient because both lists are sorted, allowing us to skip unnecessary comparisons.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers, one for each list.
- 2Step 2: Compare the current intervals pointed to by both pointers.
- 3Step 3: If they overlap, calculate the intersection and add it to the result.
- 4Step 4: Move the pointer of the interval that ends first to the next interval.
solution.py13 lines
1# Full working Python code
2result = []
3i, j = 0, 0
4while i < len(firstList) and j < len(secondList):
5 a, b = firstList[i]
6 c, d = secondList[j]
7 if a <= d and c <= b:
8 result.append([max(a, c), min(b, d)])
9 if b < d:
10 i += 1
11 else:
12 j += 1
13return resultℹ
Complexity note: This complexity is linear because we traverse each list only once, making it efficient for larger inputs.
- 1Both lists are sorted, allowing for efficient traversal with two pointers.
- 2The intersection of intervals can be calculated using max and min functions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.