Skip to content

Merge Overlapping Intervals

Andrew Burke edited this page Jan 10, 2025 · 3 revisions

JCSU Unit 5 Problem Set 1 (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Medium
  • Time to complete: 20-30 mins
  • 🛠️ Topics: Sorting, Interval Merging, List Manipulation

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • What is the goal of the problem?
    • Combine overlapping intervals into a single interval.
  • Are there constraints on input?
    • Intervals are represented as a list of two integers [start, end] where start <= end.

HAPPY CASE Input: intervals = [ [1, 3], [2, 4], [5, 7], [6, 8] ] Output: [ [1, 4], [5, 8] ] Explanation: The intervals [1, 3] and [2, 4] overlap and are merged into [1, 4]. The intervals [5, 7] and [6, 8] overlap and are merged into [5, 8].

EDGE CASE Input: intervals = [] Output: [] Explanation: An empty list results in an empty output.

EDGE CASE Input: intervals = [ [1, 2], [2, 3] ] Output: [ [1, 3] ] Explanation: The intervals [1, 2] and [2, 3] are contiguous and merged into [1, 3].

2: M-atch

Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.

For interval merging problems, we want to consider the following approaches:

  • Sorting and Iteration: Sort the intervals by their start times and iterate to merge overlaps.
  • Greedy Approach: Use the property of sorted intervals to greedily combine overlapping intervals.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea:
Sort the intervals by their starting point. Iterate through the intervals and compare each interval with the last merged interval. If they overlap, merge them by extending the end of the last merged interval. Otherwise, add the current interval as a new interval.

Steps:

  1. Check if the input intervals list is empty. If so, return an empty list.
  2. Sort the intervals by their starting points.
  3. Initialize the merged list with the first interval.
  4. Iterate through the sorted intervals starting from the second interval:
    • Compare the current interval's start with the end of the last merged interval.
    • If they overlap, update the end of the last merged interval.
    • Otherwise, add the current interval to the merged list.
  5. Return the merged list.

4: I-mplement

Implement the code to solve the algorithm.

def merge_intervals(intervals):
    if not intervals:  # Check if the input list is empty
        return []

    # Sort intervals by their starting point
    intervals.sort(key=lambda x: x[0])

    merged = [intervals[0]]  # Initialize the merged list with the first interval

    for i in range(1, len(intervals)):
        current = intervals[i]
        last_merged = merged[-1]  # Get the last interval in the merged list

        if current[0] <= last_merged[1]:  # Check if the intervals overlap
            # Merge the intervals by updating the end of the last interval
            last_merged[1] = max(last_merged[1], current[1])
        else:
            merged.append(current)  # Add the current interval as a new interval

    return merged  # Return the merged list of intervals

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.

Example 1:

  • Input: intervals = [ [1, 3], [2, 4], [5, 7], [6, 8] ]
  • Expected Output: [ [1, 4], [5, 8] ]
  • Observed Output: [ [1, 4], [5, 8] ]

Example 2:

  • Input: intervals = [ [1, 2], [2, 3] ]
  • Expected Output: [ [1, 3] ]
  • Observed Output: [ [1, 3] ]

Example 3:

  • Input: intervals = []
  • Expected Output: []
  • Observed Output: []

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Assume n is the number of intervals.

  • Time Complexity: O(n log n) for sorting the intervals, plus O(n) for iterating through them, resulting in O(n log n) overall.
  • Space Complexity: O(n) for the output list of merged intervals.
Clone this wiki locally