Start learning free

LESSON 270 OF 314 · INTERVALS

Interval List Intersections in Swift: Two Pointers in O(m + n)

Practice O(m + n) Read the full explanation

You get two arrays of intervals, first and second. Each interval is a pair [start, end]. It covers every point from its start to its end.

Return an array of 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.

Each array is sorted by start. Inside one array, no two intervals overlap or touch.

Two intervals that only touch share one point. For example, [1,4] and [4,6] overlap in [4,4].

 

Example 1:

Input: first = [[2,6],[9,12]], second = [[4,10]]
Output: [[4,6],[9,10]]
Explanation: [4,10] overlaps both intervals of first.
It shares 4 to 6 with [2,6].
It shares 9 to 10 with [9,12].

Example 2:

Input: first = [[0,3],[8,15]], second = [[3,5],[9,10],[12,12]]
Output: [[3,3],[9,10],[12,12]]
Explanation: [0,3] and [3,5] touch at 3.
[9,10] and [12,12] lie inside [8,15].
They overlap it in full.

Example 3:

Input: first = [[1,2],[7,8]], second = [[4,5]]
Output: []
Explanation: [4,5] sits in the gap between [1,2] and [7,8].
No point is in both.

 

Constraints:

  • first holds m intervals, from 0 to 100,000.
  • second holds n intervals, from 0 to 100,000.
  • Each start and end is a whole number from 0 to 1,000,000,000.
  • No start is greater than its end.
  • In each array, an interval ends before the next one starts.

Note:

Your solution should run in O(m + n) time.

STEP 1 OF 9
    Ctrl + Enter to check

    SWIFT · INTERVALS

    Interval List Intersections in Swift, explained

    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

    1. Create result, a var of type [[Int]] set to []. It must be able to grow, because we don't know how many overlaps there are.
    2. Create the two indexes i and j, both 0, in one var line.
    3. 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.
    4. Compute start with let as max(first[i][0], second[j][0]).
    5. Compute end with let as min(first[i][1], second[j][1]).
    6. If start <= end, append [start, end] to result. Using <= and not < keeps the single-point overlaps.
    7. If first[i][1] < second[j][1], add 1 to i. This is the key step: first[i] ends first.
    8. Otherwise add 1 to j. That covers second[j] ending first, and also both ending at the same point. In the tie case, moving j is enough: the next turn finds no overlap and moves i.
    9. 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 = 0 declares two variables in one statement. Both are Int and 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.count is 0) skips the loop and returns [].
    • Arrays are value types in Swift. result.append(...) changes the local result in 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 with start < end would lose this answer.
    • An empty list. With first = [] and second = [[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 i and j together 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

    firstsecondResult
    [[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]]
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free