Problem overview
The method intervalIntersection receives two arrays of intervals, first and second. Each interval is a pair [start, end] that covers every point from its start to its end, both included. Inside one array the intervals are sorted by start, and no two of them overlap or touch. The method returns the overlaps between the two arrays, from left to right. An overlap is the part that an interval of first shares with an interval of second. Two intervals that only touch share one point: [1, 4] and [4, 6] overlap in [4, 4].
For first = [[2,6],[9,12]] and second = [[4,10]] the answer is [[4, 6], [9, 10]], since [4,10] shares 4 to 6 with [2,6] and 9 to 10 with [9,12]. For first = [[1,2],[7,8]] and second = [[4,5]] the answer is empty, because [4,5] sits in the gap. Each array can hold up to 100,000 intervals, and the statement asks for O(m + n) time for m and n intervals.
Approach: two pointers, drop the interval that ends first
Comparing every interval of first with every interval of second works but costs O(m · n). Since both lists are sorted and each list has no overlaps inside it, a single walk is enough with two indexes, i into first and j into second.
For the pair first[i] and second[j], the overlap starts at the later of the two starts and ends at the earlier of the two ends. If that start is not greater than that end, the intervals share at least one point, and the overlap is [start, end]. If the start is greater, they share nothing.
Then one interval has to go. Drop the one that ends first. It is finished: every later interval in the other list starts after it ends, so nothing else can overlap it. The interval that reaches further right stays, because it may overlap the next interval of the other list. Every turn moves one pointer forward, so the loop runs at most m + n times.
Why is dropping the earlier end safe? Say first[i] ends at 6 and second[j] ends at 10. Every other interval of second after second[j] starts after 10, so it starts after 6 and can't touch first[i]. The ones before second[j] were already dropped, which means they were checked against first[i] or an earlier interval. So first[i] has nothing left to overlap, and moving past it loses no answer.
Step by step
- Create
result, avarof type[[Int]]set to[]. It must be able to grow, because we don't know how many overlaps there are. - Create the two indexes
iandj, both 0, in onevarline. - Loop while both indexes are in range:
while i < first.count && j < second.count. When one list runs out, there is nothing left to overlap. - Compute
startwithletasmax(first[i][0], second[j][0]). - Compute
endwithletasmin(first[i][1], second[j][1]). - If
start <= end, append[start, end]toresult. Using<=and not<keeps the single-point overlaps. - If
first[i][1] < second[j][1], add 1 toi. This is the key step:first[i]ends first. - Otherwise add 1 to
j. That coverssecond[j]ending first, and also both ending at the same point. In the tie case, movingjis enough: the next turn finds no overlap and movesi. - Return
result.
Tracing first = [[0,3],[8,15]] and second = [[3,5],[9,10],[12,12]] with a copy of the loop that prints each turn:
i=0 j=0 start=3 end=3 overlap
i=1 j=0 start=8 end=5 none
i=1 j=1 start=9 end=10 overlap
i=1 j=2 start=12 end=12 overlap
The first turn finds the single-point overlap [3, 3]. Then [0,3] ends before [3,5], so i moves. [8,15] and [3,5] give a start of 8 and an end of 5, so there is no overlap, and [3,5] ends first, so j moves. The last two turns overlap [8,15] with [9,10] and [12,12]. The result is [[3, 3], [9, 10], [12, 12]].
The solution in Swift
class Solution {
func intervalIntersection(_ first: [[Int]], _ second: [[Int]]) -> [[Int]] {
var result: [[Int]] = []
var i = 0, j = 0
while i < first.count && j < second.count {
let start = max(first[i][0], second[j][0])
let end = min(first[i][1], second[j][1])
if start <= end {
result.append([start, end])
}
if first[i][1] < second[j][1] {
i += 1
} else {
j += 1
}
}
return result
}
}
Swift details:
var i = 0, j = 0declares two variables in one statement. Both areIntand both are mutable.[[Int]]is an array of arrays. The empty literal[]needs the type annotation: [[Int]]so Swift knows what the array holds.- Swift prints a result such as
[[4, 6], [9, 10]]with spaces after the commas. An empty result prints as[]. - The loop condition is evaluated before every turn, so an empty list (
first.countis 0) skips the loop and returns[]. - Arrays are value types in Swift.
result.append(...)changes the localresultin place, and nothing outside the method sees it until it is returned.
Complexity
Time is O(m + n): each turn advances i or j, so the loop runs at most m + n times, with constant work per turn. Space is O(1) beyond the output itself.
Edge cases and common mistakes
- Touching intervals.
[[1,4]]and[[4,6]]give[[4, 4]]. A check withstart < endwould lose this answer. - An empty list. With
first = []andsecond = [[1,2]]the result is empty, since the loop never starts. - Identical lists.
[[1,5]]against[[1,5]]gives[[1, 5]]. - Moving both pointers every turn. Advancing
iandjtogether misses overlaps: for[[2,6],[9,12]]against[[4,10]]it returns only[[4, 6]]and loses[9, 10]. The interval that reaches further must stay for the next comparison. - Moving the one that starts first. The decision must use the ends, not the starts, because the interval with the later end is the one that can still overlap something.
Testing
| first | second | Result |
|---|---|---|
[[2,6],[9,12]] | [[4,10]] | [[4, 6], [9, 10]] |
[[0,3],[8,15]] | [[3,5],[9,10],[12,12]] | [[3, 3], [9, 10], [12, 12]] |
[[1,2],[7,8]] | [[4,5]] | [] |
[] | [[1,2]] | [] |
[[1,5]] | [[1,5]] | [[1, 5]] |
[[1,4]] | [[4,6]] | [[4, 4]] |
