intermediate7 min read·Updated September 20, 2026

Merge Overlapping Intervals Explained: Tracing [[1,3],[2,6]...]

Master interval merging through a mental model of sorting. Follow a step-by-step walkthrough of [[1,3],[2,6],[8,10],[15,18]] and handle touching bounds.

By Learnisim AI·Published September 20, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
  • Basic arrays
  • Understanding sorting algorithms
  • Conditional logic
Merging Overlapping Intervals (Sweep-Line Algorithm) Input: [[1,3], [2,6], [8,10], [15,18]] ⇒ Output: [[1,6], [8,10], [15,18]] Phase 1 & 2: Sort by Start Time & Sweep 0 2 4 6 10 15 18 [1,3] [2,6] (overlap) [8,10] [15,18] • Step 1: Sort by start time (already sorted here). • Step 2: Compare current start with last merged end. Collision detected at [2,6]! Max end becomes 6. Phase 3: Step-by-Step Merge Execution 1. Init: Push [1,3] to merged merged = [[1,3]] 2. Compare [2,6]: 2 <= 3 (Overlap!) merged[-1][1] = max(3,6) = 6 3. Compare [8,10]: 8 > 6 (No overlap) merged = [[1,6], [8,10]] 4. Compare [15,18]: 15 > 10 (No overlap) merged = [[1,6], [8,10], [15,18]] Edge Case: Touching Intervals [[1,4], [4,5]] 0 2 4 5 [1, 4] [4, 5] • Condition used: merged[-1][1] < interval[0] • Here, last end is 4, current start is 4. Since 4 < 4 is False, they trigger the else branch and merge! Result: [[1, 5]] (Endpoints 4 touch and collapse) Python Implementation def merge(intervals): intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: merged[-1][1] = max(merged[-1][1], interval[1]) Time Complexity: O(N log N) due to sorting. Space: O(N).
Merge [[1,3],[2,6],[8,10],[15,18]] and [[1,4],[4,5]] overview diagram
Why

Why We Need to Merge Overlapping Intervals

Phase 1: The Booking Collision Problem

Imagine you are building a calendar app where users can book overlapping time slots. A user submits a list of busy intervals: [[1,3], [2,6], [8,10], [15,18]]. Notice how the first interval ends at 3, but the second interval starts at 2. If you try to check availability or compute total busy time by inspecting these ranges independently, you will double-count the overlap between 2 and 3.
Without a structured way to combine these overlaps, downstream systems get overwhelmed by redundant data and incorrect durations. The problem becomes even trickier when intervals merely touch, such as [[1,4], [4,5]], where the end of the first matches the start of the second. Before we can query or analyze these ranges, we need a systematic strategy to collapse overlapping boundaries into a clean, disjoint set of timelines.
Why We Need to Merge Overlapping Intervals Solving booking collisions & double-counting in timeline data 1. Raw Input: [[1,3], [2,6], [8,10], [15,18]] Overlaps & touching endpoints cause double-counting [1, 3] [2, 6] (Overlap!) [8, 10] [15, 18] Double-counted region between 2 and 3! 2. Edge Case: [[1,4], [4,5]] (Touching) End of first matches start of next — must collapse [1, 4] [4, 5] Shared boundary at 4: merges into [1, 5] Systematic Sorting & Merge 3. Clean Disjoint Output: Accurate Timelines & Durations Overlaps collapsed, adjacent bounds joined, zero redundancy for downstream systems [1, 6] Merged overlap [8, 10] Isolated slot [15, 18] Isolated slot [1, 5] Joined touching edge
Why We Need to Merge Overlapping Intervals diagram
Model

Building the Mental Model: Sorting and Merging

Phase 2: The Timeline Sweep

When looking at our locked working example of intervals = , the human brain immediately spots that and collide because 3 passes into 2. But how do we teach a computer to see that? The core mental model relies on sorting by start time so that intervals moving forward in time are examined in chronological order.
Once sorted, we can use a single tracking window—our "current merged interval"—to sweep across the array. As we inspect each incoming interval, we only need to compare its start time against the end time of the last interval we saved. If the incoming start is less than or equal to that last end time, a collision happens, and we expand our boundary. If it is strictly greater, we know for a fact that no future interval in a sorted list can overlap with the old one, making it safe to lock in and start a new tracking window.
Building the Mental Model: Sorting and Merging Intervals Example: [[1,3], [2,6], [8,10], [15,18]] — Sweep Line Algorithm Phase 1: Sort by Start Time (Chronological Order) 0 2 3 6 8 10 15 18 [1, 3] [2, 6] (Collides!) [8, 10] [15, 18] Phase 2: The Timeline Sweep & Tracking Window Merge Condition Check • Incoming Start <= Last End? → Expand: LastEnd = max(End) • Incoming Start > Last End? → Lock in & start new window Dynamic Window Expansion Track: [1, 3] Incoming: [2, 6] Merge! Resulting Merged Output [[1, 6], [8, 10], [15, 18]] O(N log N) due to initial sort, then single O(N) linear sweep! Why the Mental Model Works Sorting guarantees that any interval starting later cannot possibly overlap with an earlier window once past its end time. ⚡ Eliminates complex nested comparisons down to a single clean forward scan!
Building the Mental Model: Sorting and Merging diagram
Worked example

Step-by-Step Walkthrough: Merging [[1,3],[2,6],[8,10],[15,18]]

Phase 3: Walking Through the Primary Example

To see the sorting and tracking mechanism in action, let us process our locked example: . Because they are already sorted by start time, we can immediately begin our single-pass sweep using a merged output list.

Given

Steps

1. Initialize: Create an empty output list . Take the first interval and push it to . Now .
2. Compare : Look at the last interval in , which is . Its end time is 3. The current interval's start time is 2. Since , an overlap occurs! Update the end time of our last merged interval to . becomes .
3. Compare : Look at the last interval . Its end time is 6. The current interval starts at 8. Since , there is no overlap. Push directly into . becomes .
4. Compare : Look at the last interval . Its end time is 10. The current interval starts at 15. Since , no overlap occurs. Push directly into .

Result

The final consolidated output is .
python
def merge(intervals):
    intervals.sort(key=lambda x: x[0])
    merged = []
    for interval in intervals:
        if not merged or merged[-1][1] < interval[0]:
            merged.append(interval)
        else:
            merged[-1][1] = max(merged[-1][1], interval[1])
    return merged
Phase 3 Walkthrough: [[1,3], [2,6], [8,10], [15,18]] Single-pass sweep comparing last merged end time with current interval start 1 2 3 6 8 10 15 18 Input: [1, 3] [2, 6] (Overlap! 2 <= 3) [8, 10] [15, 18] merged = [1, 6] Merged [1,3] & [2,6] [8, 10] No overlap (8 > 6) [15, 18] No overlap (15 > 10) Rule Check during sweep: • If merged[-1][1] < interval.start: Push new interval directly. • Else (Overlap!): Update last end time to max(last.end, interval.end). Final Output: [[1,6], [8,10], [15,18]]
Step-by-Step Walkthrough: Merging [[1,3],[2,6],[8,10],[15,18]] diagram
Practice

Practice: Predicting an Unsorted Overlapping Input

Phase 4: Practice Your Tracking Skills

Now that you have seen how the primary intervals move through the accumulator stack step by step, it is time to test your hand at a slightly mutated variation. Real-world data is rarely polite enough to arrive sorted by start times.
Consider what happens when our working intervals are scrambled and contain a tightly touching boundary. Take the input array [[8,10], [1,3], [15,18], [2,6]]. Notice two things immediately: the array is completely out of order, and the first two intervals overlap.
Work through this on scratch paper or mentally using the two rules established in our mental model:
1.Ensure the array is sorted by start values.

2. Compare each incoming interval against the last interval in your output accumulator, merging when current.start <= last.end.

The Practice Task

Given the scrambled interval list [[8,10], [1,3], [15,18], [2,6]], write out or trace the exact state of your output array after:
•Step A: The sorting phase completes.
•Step B: The final merged result is produced.
Compare your intermediate sorted array against our original locked example to confirm why sorting is the non-negotiable prerequisite for linear merging.
python
def trace_practice_intervals():
    # Scrambled input containing our working intervals
    intervals = [[8, 10], [1, 3], [15, 18], [2, 6]]
    
    # TODO: Sort by start time, then merge overlapping elements
    pass
Apply

Applying the Sorting and Merging Pattern to Meeting Rooms

Phase 5: Transfer

Now that you have mastered how the working intervals [[1,3],[2,6],[8,10],[15,18]] collapse into consolidated blocks by sorting and comparing endpoints, you can apply this exact mechanical pattern to entirely different domains. The underlying algorithm does not care whether your numbers represent time blocks on a calendar, memory addresses, or printer reservations; it only cares about start and end coordinates. Whenever you face a problem where contiguous or overlapping spans must be combined or checked for capacity collisions, the sort-by-start strategy remains your primary tool.
Consider how you would determine if a single person's schedule has any overlapping bookings that prevent them from attending meetings back-to-back without travel time. If a meeting ends at time 4 and the next starts at time 4, our previous touching rule proved they meet at the boundary. But what if your domain requires a strict gap of at least 1 unit of time between events? You can adapt the core condition from cur.start <= last.end to account for that buffer, proving the versatility of the mental model you built.
python
def min_meeting_rooms(intervals):
    # TODO: Apply interval merging or sorting logic 
    # to solve a scheduling variant.
    pass

FAQ

What is the result of merging [[1,3],[2,6],[8,10],[15,18]]?
The result is [[1,6],[8,10],[15,18]]. Because [1,3] and [2,6] overlap (2 is less than or equal to 3), they combine into [1,6].
How do touching intervals like [1,4] and [4,5] behave?
Touching intervals merge into [1,5] because the end of the first interval (4) equals the start of the second interval.
Why is sorting required before merging intervals?
Sorting by start times ensures that overlapping intervals appear adjacently, allowing us to evaluate them in a single linear pass.
What is the time complexity of the merge intervals algorithm?
The time complexity is O(N log N) due to the initial sorting step, followed by an O(N) linear scan to merge them.

Keep learning