AlgoTales · Roadmap

Merge intervals

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Merge intervals sorts time slots or ranges by start and joins any that overlap into bigger ones. What you get is a short, tidy list showing exactly which stretches are covered and which gaps remain.

Practical use cases

  • Web app: Free and busy view in a calendar app. A booking page for a consultant combines meetings from several calendars. Sorting by start and merging overlaps gives the true busy blocks, and the gaps between them become the slots offered to clients. Clients see only real open slots, and the consultant is not double-booked.
  • Web app: Wedding hall diary. A venue owner enters bookings over time, some overlapping by mistake. Merging shows the days that are blocked in one clean list and highlights double-booked stretches. The owner sees a clean diary with double bookings highlighted, instead of a confusing list.
  • Web app: Blocked IP ranges in an admin panel. A security page stores hundreds of blocked IP ranges that grew by copy-paste. Merging them gives a small list that is faster to check on every request. Each request is checked against a short list, so the site stays quick even when under attack.
  • System: Video timelines and memory ranges. Video editors merge overlapping clips on a track, and operating systems merge adjacent free memory or disk areas into larger ones. The same merging keeps timelines and memory maps tidy, so large free areas can be reused instead of being split into useless scraps.

The story: The Wedding Hall Diary

Zoya’s uncle ran a small wedding hall, and his booking diary was a disaster. Pages were filled in whenever a phone call came, so the entries were in no order at all: "Sangeet 8 to 10", "Mehendi 1 to 3", "Reception 15 to 18", "Haldi 2 to 6". The cleaner kept asking: "Sir, when is the hall actually busy? When can I mop?"

Zoya tried to compare every entry with every other entry. Four entries meant six comparisons, forty entries meant hundreds, and she still missed that Haldi 2 to 6 sat on top of Mehendi 1 to 3. Her head was spinning. Then Grandpa Bhaskar said: "Child, you are doing it the hard way. Put the pages in order of start time first."

Once sorted, magic: Mehendi 1-3, Haldi 2-6, Sangeet 8-10, Reception 15-18. Now an overlap can only happen with the booking right before it. Haldi starts at 2, before 3 ends, so the two stretch into one block, 1 to 6. Sangeet starts at 8, after 6, so it is a new block. One pass, done.

This is the merge intervals pattern. And here is the smell: whenever a problem says "overlapping", "ranges", "meetings", "bookings", "time slots", "merge", think: sort by start, then sweep and stretch the last block.

How to spot this problem, and where you need it

You have many ranges that overlap or touch and you want one clean list of covered ranges, or the gaps in between.

Signs you need it

  • The data is [start, end] pairs and the task says "merge", "combine overlapping", "free time" or "total covered time".
  • The list displayed to users contains duplicated or overlapping blocks that should be one.
  • You compare each range to every other range to see whether they overlap.

Where to use it in a project

  • Availability and booking screens that must show free and busy slots.
  • Cleaning stored date, price or IP ranges that overlap or touch each other.
  • Working out total covered time, such as total hours a machine was busy.

The solution

Sort ranges by start. Take the first as your current block. For each next range: if its start is not beyond the current end, they overlap, so extend the current end to the larger of the two ends; otherwise save the current block and start a new one. After the last range, save the last block. Gaps are the spaces between saved blocks.

Payoff: Before: 10,000 ranges compared in pairs. After: one sort and one pass, giving perhaps 50 clean blocks.

Explain it like I am 8

Imagine colouring bars on a long ruler with crayons, in random order. If you first line the bars up from left to right, you only need to ask one thing: "does this bar touch the one I just coloured?" If yes, make it longer. If not, start a new bar.

How it works, step by step

  1. Spot the clue: the problem talks about ranges, meetings or time slots that may overlap. That is the merge-intervals smell.
  2. Sort by start (usort / sort). Without this the pattern does not work.
  3. Keep a result list. Put the first interval in it.
  4. For each next interval: if its start is <= the end of the last merged block, stretch that block's end with max(oldEnd, newEnd). Otherwise append it as a new block.
  5. Return the result. The same sorted sweep also answers "how many meeting rooms?", "insert a new interval" and "find free gaps".

The code in four languages

PHP

<?php
// Classic: "Merge Intervals". Sort by start, then sweep once.
function mergeIntervals(array $intervals): array {
    usort($intervals, fn($a, $b) => $a[0] <=> $b[0]);   // step 1: order by start time
    $merged = [];
    foreach ($intervals as $cur) {
        $last = count($merged) - 1;
        if ($last >= 0 && $cur[0] <= $merged[$last][1]) {
            // overlaps the last block: stretch it (never shrink it!)
            $merged[$last][1] = max($merged[$last][1], $cur[1]);
        } else {
            $merged[] = $cur;                           // a gap: start a new block
        }
    }
    return $merged;
}
echo json_encode(mergeIntervals([[8, 10], [1, 3], [15, 18], [2, 6]])), "
";   // [[1,6],[8,10],[15,18]]
echo json_encode(mergeIntervals([[1, 10], [2, 3]])), "
";                    // [[1,10]]  (one inside another)

JavaScript

// Classic: "Merge Intervals". Sort by start, then sweep once.
function mergeIntervals(intervals) {
  const sorted = [...intervals].sort((a, b) => a[0] - b[0]);   // step 1: order by start time
  const merged = [];
  for (const cur of sorted) {
    const last = merged[merged.length - 1];
    if (last && cur[0] <= last[1]) {
      // overlaps the last block: stretch it (never shrink it!)
      last[1] = Math.max(last[1], cur[1]);
    } else {
      merged.push([cur[0], cur[1]]);                           // a gap: start a new block
    }
  }
  return merged;
}
console.log(JSON.stringify(mergeIntervals([[8, 10], [1, 3], [15, 18], [2, 6]])));   // [[1,6],[8,10],[15,18]]
console.log(JSON.stringify(mergeIntervals([[1, 10], [2, 3]])));                    // [[1,10]]  (one inside another)

Java

import java.util.*;

public class Main {
    // Classic: "Merge Intervals". Sort by start, then sweep once.
    static List<int[]> mergeIntervals(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0]));   // step 1: order by start time
        List<int[]> merged = new ArrayList<>();
        for (int[] cur : sorted) {
            if (!merged.isEmpty() && cur[0] <= merged.get(merged.size() - 1)[1]) {
                // overlaps the last block: stretch it (never shrink it!)
                int[] last = merged.get(merged.size() - 1);
                last[1] = Math.max(last[1], cur[1]);
            } else {
                merged.add(new int[]{cur[0], cur[1]});                // a gap: start a new block
            }
        }
        return merged;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(mergeIntervals(new int[][]{{8, 10}, {1, 3}, {15, 18}, {2, 6}}).toArray()));   // [[1, 6], [8, 10], [15, 18]]
        System.out.println(Arrays.deepToString(mergeIntervals(new int[][]{{1, 10}, {2, 3}}).toArray()));                    // [[1, 10]]  (one inside another)
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

// mergeIntervals is the classic "Merge Intervals". Sort by start, then sweep once.
func mergeIntervals(intervals [][2]int) [][2]int {
	sorted := slices.Clone(intervals)
	slices.SortFunc(sorted, func(a, b [2]int) int { return a[0] - b[0] }) // step 1: order by start time
	var merged [][2]int
	for _, cur := range sorted {
		if n := len(merged); n > 0 && cur[0] <= merged[n-1][1] {
			// overlaps the last block: stretch it (never shrink it!)
			merged[n-1][1] = max(merged[n-1][1], cur[1])
		} else {
			merged = append(merged, cur) // a gap: start a new block
		}
	}
	return merged
}

func main() {
	fmt.Println(mergeIntervals([][2]int{{8, 10}, {1, 3}, {15, 18}, {2, 6}})) // [[1 6] [8 10] [15 18]]
	fmt.Println(mergeIntervals([][2]int{{1, 10}, {2, 3}}))                   // [[1 10]]  (one inside another)
}

Time: O(n log n) · Extra space: O(n). The sort costs the most; the sweep after it is a single O(n) pass.

Watch out for

  • Forgetting to sort first. On unsorted data the "only compare with the last block" shortcut gives wrong answers.
  • Setting the end to the new interval's end instead of max(oldEnd, newEnd). [1,10] followed by [2,3] would wrongly shrink to [1,3].
  • Using < when touching intervals like [1,3] and [3,5] should merge. Read the problem: usually <=.

Quick check

  1. Which clue word tells you to try merge intervals?
    • "overlapping meetings"
    • "shortest path"
    • "sorted array, find target"
    • "all permutations"
  2. After sorting by start, what do you compare each new interval with?
    • Every earlier interval
    • Only the first interval
    • Only the last merged block
    • The longest interval
  3. When the new interval overlaps, the merged end becomes...
    • the new end
    • max(old end, new end)
    • the old end
    • the start of the new one