Taro Logo

Merge Intervals

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+81
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
7.3K views
Topics:
ArraysGreedy Algorithms

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Constraints:

  • 1 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 104

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. Are the input intervals guaranteed to be sorted by their start times, or should I handle unsorted input?
  2. What should be the output format if the input array is empty or null?
  3. Can the start and end values be negative numbers, or are they strictly non-negative?
  4. What constitutes an 'overlapping' interval? For example, do intervals like `[1, 2]` and `[2, 3]` overlap?
  5. Should the resulting merged intervals be returned in any specific sorted order (e.g., ascending by start time)?

Brute Force Solution

Approach

Imagine you have a messy pile of time periods that overlap with each other, and you want to clean them up by combining the ones that touch or overlap. The brute force approach involves exhaustively comparing every single period against every other period to find overlaps, combining them, and repeating the process until nothing else can be combined.

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

  1. Pick one time period from your pile to start.
  2. Compare this chosen period against every other period in the pile to see if any of them overlap or touch.
  3. If you find a pair that overlaps, merge them into a single, brand new combined period, and throw away the two original ones.
  4. Take this newly combined period and repeat the entire checking process with all the remaining periods in the pile.
  5. If you check a period against everything else and find zero overlaps, set that period aside as finished and safe.
  6. Keep repeating this cycle of comparing, merging, and setting aside until you have thoroughly checked every single thing against everything else and no more overlaps exist.
  7. Gather all your finished, non-overlapping periods together as your final answer.

Code Implementation

def merge(intervals):
    active_intervals = list(intervals)
    
    # We loop indefinitely because merging can create new overlaps requiring another pass
    while True:
        merged_something = False
        
        for current_index in range(len(active_intervals)):
            if merged_something:
                break
                
            for other_index in range(current_index + 1, len(active_intervals)):
                first_interval = active_intervals[current_index]
                second_interval = active_intervals[other_index]
                
                # Check if intervals overlap to determine if they need to be combined into one
                if not (first_interval[1] < second_interval[0] or second_interval[1] < first_interval[0]):
                    combined_start = min(first_interval[0], second_interval[0])
                    combined_end = max(first_interval[1], second_interval[1])
                    new_interval = [combined_start, combined_end]
                    
                    active_intervals.pop(other_index)
                    active_intervals.pop(current_index)
                    active_intervals.append(new_interval)
                    merged_something = True
                    break
                    
        # Terminate loop only when a full pass completes without triggering any merges
        if not merged_something:
            return active_intervals

Big(O) Analysis

Time Complexity
O(n²) – For each of the n time periods in the input pile, the brute force approach exhaustively compares it against every other remaining period to check for overlaps. In the worst case where no intervals merge immediately, we perform roughly n-1 comparisons for the first period, n-2 for the second, and so on. This nested comparison cycle leads to approximately n * n / 2 total operations, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(N) – The brute force approach described relies on gathering items into a pile of finished, non-overlapping periods and storing intermediate combined results as we repeatedly compare and throw away original intervals. In the worst-case scenario where no intervals overlap, this final collection will store all N original intervals. Therefore, the auxiliary data structures required to gather and hold the final answer scale linearly with the input size N. Simplifying this to Big O notation yields O(N) auxiliary space complexity.

Optimal Solution

Approach

To efficiently combine overlapping periods, we first organize them by their starting times so we can process them in chronological order. As we go through them one by one, we either merge overlapping periods into a single larger period or keep them separate if they do not touch.

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

  1. Gather all the time periods together and arrange them in order from earliest starting time to latest starting time.
  2. Take the first period and set it aside as our current working period.
  3. Look at the very next period in line to see if it starts before our current working period ends.
  4. If the next period starts during or before our current working period, stretch our current period so that it covers the end of this new period as well.
  5. If the next period starts after our current working period ends, it means there is a gap, so we save our current period as final and make this new period our current working focus.
  6. Repeat this comparison process for every period in the entire lineup.
  7. Once you reach the end of the line, save the final working period to complete the complete set of combined periods.

Code Implementation

class Solution:
    def merge(self, intervals: list[list[int]]) -> list[list[int]]:
        if not intervals:
            return []

        # Sorting by start time ensures chronological order for proper overlap checking.
        sorted_intervals = sorted(intervals, key=lambda current_interval: current_interval[0])

        merged_intervals = [sorted_intervals[0]]

        for current_interval in sorted_intervals[1:]:
            latest_merged_interval = merged_intervals[-1]

            # Overlapping intervals require merging to create a single continuous period.
            if current_interval[0] <= latest_merged_interval[1]:
                latest_merged_interval[1] = max(latest_merged_interval[1], current_interval[1])

            else:
                # Non-overlapping intervals mean we finalize the current and start a new one.
                merged_intervals.append(current_interval)

        return merged_intervals

Big(O) Analysis

Time Complexity
O(n log n) – The primary cost driving the time complexity is sorting the intervals by their starting times, which takes O(n log n) time for n intervals. Afterward, a single sequential pass through the sorted array processes every interval exactly once in linear O(n) time. The total operations are dominated by the sorting step, so adding O(n log n) and O(n) simplifies to an overall Big O runtime of O(n log n).
Space Complexity
O(N) – The space complexity is driven by the output list that stores the merged intervals, where N is the number of intervals in the input. In the worst-case scenario where no intervals overlap, this result list will store all N intervals. Additionally, sorting the intervals in place requires auxiliary space depending on the sorting algorithm implementation, typically ranging from O(log N) to O(N) stack or array space. Combining the storage for the merged intervals and the sorting overhead results in a total auxiliary space complexity of O(N).

Edge Cases

Empty input array
How to Handle:
Return the empty array immediately without performing any operations.
Single interval array
How to Handle:
Return the single interval directly as no merging is required.
Completely overlapping intervals
How to Handle:
The merge logic absorbs smaller intervals inside the larger one and produces a single combined interval.
Disjoint intervals
How to Handle:
The sorting step ensures they remain separate and are appended to the result without modification.
Intervals with negative numbers
How to Handle:
Standard sorting and comparison naturally handle negative coordinate values.
Touch-only intervals where one ends at the exact start of another
How to Handle:
Using a condition like current_start <= previous_end successfully merges touching boundaries.
Duplicate intervals
How to Handle:
Sorting groups them together and the merge logic safely combines them into one.
Maximum possible integer values for start and end times
How to Handle:
Ensure comparison logic avoids overflow in languages with fixed-width integers.
0/75 completed