Taro Logo

Merge Intervals

#16 Most AskedMedium
24 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 an unsorted array?
  2. What should be returned if the input array is empty or null?
  3. Can interval start and end values be negative, or are they strictly non-negative integers?
  4. How should we treat intervals that merely touch at a single endpoint, such as [1, 2] and [2, 3]? Should they be merged into [1, 3]?
  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 see if any two can be glued together.

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 with every other period in the pile to check if they overlap or touch.
  3. If you find another period that connects with your chosen one, glue them together into a single, longer period.
  4. Whenever you successfully glue two periods together, replace them in your mind with the new combined period and start the whole comparison process all over again from the beginning.
  5. Keep comparing every pair of periods and gluing them whenever possible.
  6. Repeat this entire checking and gluing process until you go through a complete round where no more overlapping periods can be found.
  7. Once nothing else can be combined, the remaining periods represent your final cleaned-up list.

Code Implementation

def merge(intervals):
    merged_intervals_list = list(intervals)

    # We loop continuously until a full pass completes without any overlapping merges
    while True:
        intervals_were_merged = False
        
        for current_index in range(len(merged_intervals_list)):
            for comparison_index in range(current_index + 1, len(merged_intervals_list)):
                first_interval = merged_intervals_list[current_index]
                second_interval = merged_intervals_list[comparison_index]

                # Overlap check ensures we only combine intervals that actually touch or intersect
                if (first_interval[0] <= second_interval[1]) and (second_interval[0] <= first_interval[1]):
                    new_start_value = min(first_interval[0], second_interval[0])
                    new_end_value = max(first_interval[1], second_interval[1])
                    combined_interval = [new_start_value, new_end_value]

                    merged_intervals_list.pop(comparison_index)
                    merged_intervals_list.pop(current_index)
                    merged_intervals_list.append(combined_interval)

                    intervals_were_merged = True
                    break

            # Restarting the loop is necessary because list mutations invalidate current indexes
            if intervals_were_merged:
                break

        # Terminate the while loop only when a complete iteration finds no overlapping pairs
        if not intervals_were_merged:
            break

    return merged_intervals_list

Big(O) Analysis

Time Complexity
O(n²) – For each of the n time periods in the input pile, the algorithm exhaustively compares it against every other period to check for overlaps. Because a successful merge restarts the entire comparison process from the beginning, we repeatedly check pairs across multiple rounds until no more combinations are found. This nested checking and restarting behavior yields approximately n * n/2 total operations in the worst case, which simplifies to O(n²).
Space Complexity
O(N) – The brute force and optimal approaches both require storing the final merged intervals in a separate output list, where N represents the number of intervals in the input pile. In the worst-case scenario where no intervals overlap, this result list will store all N intervals. Additionally, standard sorting algorithms used to organize the pile prior to merging can require up to O(N) auxiliary space for the call stack or temporary buffers. Therefore, the extra memory required grows linearly with the input size N, independent of the input itself.

Optimal Solution

Approach

To efficiently combine overlapping time blocks, we first organize all the blocks in chronological order based on when they start. Then, we walk through them from left to right, smoothly blending overlapping neighbors into a single continuous block.

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

  1. Gather all the time blocks and line them up neatly from left to right based on their starting times.
  2. Create a fresh, empty collection to hold your final, cleanly merged blocks of time.
  3. Take the very first time block and place it into your final collection to kick things off.
  4. Look at the next block in line and compare it against the most recent block you added to your final collection.
  5. Check if the starting time of this current block happens before or at the exact same moment the most recent final block ends.
  6. If they overlap, stretch the end time of that most recent final block so it covers the entire duration of both.
  7. If they do not overlap, simply treat the current block as a brand-new independent block and add it to your final collection.
  8. Repeat this comparison and merging process for every remaining block until you reach the end of the line.

Code Implementation

def merge(intervals):
    # Sorting by start time ensures overlapping blocks become adjacent neighbors.
    sorted_intervals = sorted(intervals, key=lambda interval: interval[0])
    
    merged_intervals = [sorted_intervals[0]]
    
    for current_block in sorted_intervals[1:]:
        most_recent_block = merged_intervals[-1]
        
        # Overlapping blocks must be merged to maintain contiguous time ranges.
        if current_block[0] <= most_recent_block[1]:
            most_recent_block[1] = max(most_recent_block[1], current_block[1])
        
        # Non-overlapping blocks start a new independent range in the result.
        else:
            merged_intervals.append(current_block)
            
    return merged_intervals

Big(O) Analysis

Time Complexity
O(n log n) – The time complexity is driven by sorting the n intervals chronologically based on their start times, which takes O(n log n) operations. Afterward, we iterate through the sorted list of n intervals a single time to merge overlapping neighbors, requiring linear O(n) time. Since the logarithmic sorting step dominates the linear traversal, the total operations simplify to O(n log n).
Space Complexity
O(n) – The space complexity is driven by the final output collection and the sorting algorithm's internal memory. Specifically, the output list stores up to N merged intervals in the worst-case scenario where no intervals overlap. Additionally, depending on the language's implementation, the sorting step requires auxiliary stack space of O(n) to organize the intervals chronologically. Therefore, the total extra memory grows linearly with the input size N.

Edge Cases

Empty input array
How to Handle:
Check for null or empty array at the very beginning and return an empty array immediately.
Single interval in the input
How to Handle:
Sorting and iteration skip the merge loop and safely return the single interval unchanged.
All intervals are already non-overlapping
How to Handle:
Each interval is compared, fails the overlap condition, and is simply added to the output result list.
All intervals completely overlap into one large interval
How to Handle:
The algorithm continuously updates the end time of a single running interval until all elements are merged.
Intervals with negative numbers and zero
How to Handle:
Sorting handles negative numbers naturally because they evaluate smaller than zeros and positive values.
Intervals sharing exact boundary points like [1, 4] and [4, 6]
How to Handle:
The merge condition uses less than or equal to the current end against the next start to successfully combine touching intervals.
Completely nested intervals such as [1, 5] and [2, 4]
How to Handle:
Tracking the maximum end time across overlapping intervals prevents premature closing when a smaller interval is nested inside.
Extremely large inputs scaling near memory limits
How to Handle:
An in-place or O(N log N) sorting approach ensures efficient time complexity while keeping auxiliary space minimal.
0/66 completed