Back to course sections
    Mark As Completed Discussion

    Merging Intervals: A Detailed Walkthrough

    Let's get our hands dirty by stepping through the actual code to merge the given list of intervals: [[1, 4], [2, 5], [7, 10], [12, 16]].

    Preparing the Ground: Initial Sort and Setup

    Before jumping into merging, we sort our intervals by their start times.

    PYTHON
    1intervals = [[1, 4], [2, 5], [7, 10], [12, 16]]
    2intervals.sort(key=lambda x: x[0])

    Also, initialize an empty array called result to store the merged intervals.

    PYTHON
    1result = []

    Step 1: Seed the result Array

    We start by taking the first interval [1, 4] from our sorted array and appending it to result.

    PYTHON
    1result.append(intervals[0])

    At this point, result = [[1, 4]].

    Step 2: Enter the Loop: First Iteration

    Now, we loop through the remaining intervals in the sorted array, starting with [2, 5].

    PYTHON
    1current = [2, 5]
    2last = result[-1]  # [1, 4]

    Here, last is [1, 4], and current is [2, 5]. We notice that current[0] <= last[1], which indicates an overlap. So, we extend last to cover current.

    PYTHON
    1if current[0] <= last[1]:
    2    last[1] = max(current[1], last[1])  # max(5, 4) = 5

    After this step, result = [[1, 5]].

    Step 3: Second Iteration

    Next, we consider the interval [7, 10].

    PYTHON
    1current = [7, 10]
    2last = result[-1]  # [1, 5]

    Here, current[0] > last[1], meaning there's a gap. So, we simply append current to result.

    PYTHON
    1result.append(current)

    Now, result = [[1, 5], [7, 10]].

    Step 4: Final Iterations

    We repeat the above steps for [12, 16]. Since it doesn't overlap with the last interval [7, 10], we add it to the result as is.

    PYTHON
    1result.append([12, 16])

    Our final result array becomes [[1, 5], [7, 10], [12, 16]].

    And there you have it! We've successfully merged the intervals using Python code. This step-by-step walkthrough should give you a detailed understanding of how interval merging works in practice.

    Walkthrough Example