Taro Logo

Interval List Intersections

#7 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.

Return the intersection of these two interval lists.

A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.

The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].

Example 1:

Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]

Example 2:

Input: firstList = [[1,3],[5,9]], secondList = []
Output: []

Constraints:

  • 0 <= firstList.length, secondList.length <= 1000
  • firstList.length + secondList.length >= 1
  • 0 <= starti < endi <= 109
  • endi < starti+1
  • 0 <= startj < endj <= 109
  • endj < startj+1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected data type of the interval boundaries (e.g., standard 32-bit integers, 64-bit longs, or floating-point numbers)?
  2. How should we handle empty input lists (e.g., if either `firstList` or `secondList` is empty), and should we return an empty list in that case?
  3. Can the intervals in the input be point-intervals (where the start time equals the end time, such as `[3, 3]`), and are such point intersections valid?
  4. Are the input intervals guaranteed to be strictly valid (i.e., `start <= end` for every interval), or do I need to validate them?
  5. Is there any specific memory or space complexity constraint we need to adhere to beyond returning the new list of intersections?

Brute Force Solution

Approach

Imagine you are given two separate schedules of busy times and need to find when both schedules overlap. The brute force approach involves comparing every single time block from the first schedule against every single time block from the second schedule to see if they share any common moments.

Here's how the algorithm would work step-by-step:

  1. Take the first time block from the first schedule.
  2. Compare this block against every single time block in the second schedule, one by one.
  3. For each pairing, check if the two blocks overlap by seeing if one starts before the other ends and ends after the other starts.
  4. If they overlap, write down the exact starting and ending points where they cross over.
  5. Move on to the next time block in the first schedule and repeat the process of checking it against every block in the second schedule.
  6. Continue this exhaustive process until every possible pair of time blocks from both schedules has been checked.
  7. Gather all the overlapping moments you found during these comparisons and present them as your final result.

Code Implementation

def interval_intersection(first_schedule, second_schedule):
    overlapping_intervals = []

    # Compare every time block from the first schedule against every block in the second schedule
    for first_interval in first_schedule:
        for second_interval in second_schedule:
            
            # Determine the overlap bounds by finding the latest start time and earliest end time
            start_maximum = max(first_interval[0], second_interval[0])
            end_minimum = min(first_interval[1], second_interval[1])
            
            # If the start is less than or equal to the end, a valid overlap exists
            if start_maximum <= end_minimum:
                overlapping_intervals.append([start_maximum, end_minimum])

    return overlapping_intervals

Big(O) Analysis

Time Complexity
O(n * m) – For each of the n time blocks in the first schedule, the brute force approach exhaustively checks all m time blocks in the second schedule to see if they overlap. This requires a nested comparison where every block from the first list is paired against every block from the second list. Assuming both lists have a comparable size n, this results in approximately n * n comparisons. Simplifying this multiplicative growth of operations yields a final Big O time complexity of O(n * m), or O(n²) when both schedules are of equal length.
Space Complexity
O(N) – The space complexity is driven by the final output list that gathers all the overlapping moments found during the comparisons between the two schedules. In the worst-case scenario, every time block from one schedule could overlap with blocks from the other, leading to a collection of intersections proportional to the total number of input intervals, denoted as N. Therefore, the extra memory required grows linearly with the size of the inputs to store these intermediate and final overlapping segments. This results in an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

To find the overlapping times between two schedules, we can compare them side by side from beginning to end. By looking at the earliest meetings from both lists simultaneously, we can instantly spot any shared time and naturally advance past the meeting that finishes sooner.

Here's how the algorithm would work step-by-step:

  1. Lay out both schedules side by side so you can look at the very first meeting from each list.
  2. Compare the two current meetings to see if they overlap by checking if the later start time happens before the earlier end time.
  3. If they do overlap, figure out the shared window by taking the later start time and the earlier end time, then save this as a valid match.
  4. Determine which of the two meetings finishes first in time, because that meeting cannot possibly overlap with anything else coming up.
  5. Move past the meeting that finished first by looking at the next scheduled meeting in that specific list.
  6. Keep repeating this side by side comparison until you run out of meetings on either schedule.

Code Implementation

def interval_intersection(first_schedule, second_schedule):
    matched_intersections = []
    first_index = 0
    second_index = 0

    while first_index < len(first_schedule) and second_index < len(second_schedule):
        first_interval = first_schedule[first_index]
        second_interval = second_schedule[second_index]

        latest_start = max(first_interval[0], second_interval[0])
        earliest_end = min(first_interval[1], second_interval[1])

        # An overlap exists only if the latest start time precedes the earliest end time.
        if latest_start <= earliest_end:
            matched_intersections.append([latest_start, earliest_end])

        # Advance the pointer of the interval that finishes first, as it cannot overlap further.
        if first_interval[1] < second_interval[1]:
            first_index += 1
        else:
            second_index += 1

    return matched_intersections

Big(O) Analysis

Time Complexity
O(n + m) – The cost is driven by a single pass through both interval lists simultaneously, where n is the number of intervals in the first list and m is the number of intervals in the second list. At each step of our side by side comparison, we advance our pointer in either the first or the second list based on which interval ends sooner. Because each interval is visited and processed at most once, the total number of operations scales linearly with the combined input sizes. This operations total approximates n + m steps directly, which simplifies to O(n + m) time complexity.
Space Complexity
O(N) – The auxiliary space complexity is driven by the dynamic result list that stores the overlapping intersection intervals, where N represents the total number of intervals across both input lists. In the worst-case scenario, every interval in one list overlaps with an interval in the other list, causing the output list to store up to N pairs of start and end times. Aside from this resulting collection, only a constant number of pointer variables are used to iterate through the schedules side by side. Therefore, the extra memory required scales linearly with the number of generated intersections, simplifying in Big O notation to O(N).

Edge Cases

One or both interval lists are empty
How to Handle:
The two-pointer loop condition fails immediately, returning an empty result list as expected.
Intervals with zero length where start equals end
How to Handle:
Point intervals are correctly processed by the overlap logic since closed intervals include single-point intersections.
Intervals contain negative numbers
How to Handle:
Standard numerical comparisons work correctly for negative ranges without requiring coordinate transformations.
Completely disjoint interval lists with no overlaps
How to Handle:
The pointer advancement logic correctly skips non-overlapping intervals until one list is fully traversed.
One list completely encompasses intervals from the other list
How to Handle:
The inner pointer advances only after the fully contained interval is completely compared against the larger enclosing interval.
Maximum sized inputs with thousands of intervals
How to Handle:
The two-pointer linear scan approach scales efficiently operating in O(N + M) time complexity without recursion overhead.
Extreme boundary values reaching integer limits
How to Handle:
Using standard 32-bit or 64-bit integers safely handles maximum boundary values without arithmetic overflow during comparisons.
0/29 completed