AlgoTales · Roadmap

Merge intervals

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

Where you will meet this in real life

Merging intervals combines overlapping ranges, such as times, dates or number ranges, into the smallest set of non-overlapping ones. Sort by start, then keep stretching the current range while the next one touches it.

Practical use cases

  • Web app: Calendar busy and free view. A scheduling page shows when a person is busy. Meetings like 9 to 10, 9:30 to 11 and 10:45 to 12 merge into one block of 9 to 12, so the free-time picker shows clean gaps instead of a cluttered list.
  • Web app: Hotel or rental availability. A booking site stores each reservation as check-in and check-out dates. Merging overlapping and touching bookings gives the blocked-out periods, and the date picker greys them out. Guests cannot pick a date that is already taken, and the owner sees their blocked periods as a few clean bars instead of a long list.
  • Web app: IP allow-list cleanup. A firewall admin page has dozens of IP ranges from different rules. Merging overlaps reduces them to a few, making the list shorter to review and quicker to check. Reviewers read five clean ranges instead of fifty overlapping ones.
  • System: Genome ranges and video timelines. Bioinformatics tools merge overlapping gene regions, and video editors merge overlapping clips on a timeline into continuous segments. In each of these the work is the same: sort by start, then keep stretching the current range as long as the next one touches it.

The story: Kabir and the Community Room

The mohalla had one community room, used for birthdays, yoga classes and Diwali meetings. Kabir kept the booking register, and every entry looked like "from 1 to 3", "from 2 to 6", "from 8 to 10". The notebook was messy, and some bookings overlapped because two families had agreed to share.

The secretary wanted a simple question answered: "When is the room busy at all?" Kabir stared at the crowded page. Slot 1-3 and slot 2-6 clearly shared the hours 2 to 3, so together they meant "busy from 1 to 6".

Mira suggested the trick: "First sort the bookings by start time. Then walk through them one by one. Keep the current busy block. If the next booking starts before or exactly when the block ends, stretch the block's end if needed. If it starts after, close the block and start a new one."

In one pass, five scribbles turned into three tidy periods: 1-6, 8-10 and 15-20. This is merging intervals, a small greedy step that appears everywhere calendars, timelines and ranges are involved.

How to spot this problem, and where you need it

You have a list of ranges that overlap or touch, and you need a clean list of non-overlapping ranges, or a simple answer about total covered time.

Signs you need it

  • Data has start and end values (times, dates, numbers, IPs) and the display or logic is messy because ranges overlap.
  • You are comparing every range with every other range in nested loops to find overlaps.
  • The question is "total busy time", "free gaps" or "combine overlapping".

Where to use it in a project

  • Calendar, availability and booking date pickers that must show blocked periods.
  • Cleaning up rule lists such as IP ranges, discount periods or price bands.

The solution

Sort the ranges by start. Put the first range in a result list. For each next range, compare its start with the end of the last range in the result: if it starts at or before that end, they overlap, so set the last end to the larger of the two ends; otherwise add it as a new range. After one pass, the result holds the merged ranges.

Payoff: Before: nested loops comparing 2,000 ranges pairwise, millions of checks. After: one sort and one pass, about 2,000 steps.

Explain it like I am 8

Imagine painting stripes on a fence. When two stripes overlap, they just become one bigger stripe. Sort the stripes from left to right and keep stretching the current stripe whenever the next one touches it.

How it works, step by step

  1. Sort the intervals by their start.
  2. Start the answer list with the first interval.
  3. For each next interval, compare its start with the end of the last merged interval.
  4. If start <= lastEnd, they overlap: stretch the last end to max(lastEnd, end).
  5. Otherwise there is a gap: add a new interval to the answer.

The code in four languages

PHP

<?php
// Merge all overlapping [start, end] intervals.
function mergeIntervals(array $iv): array {
    usort($iv, fn($a, $b) => $a[0] <=> $b[0]);     // sort by start
    $merged = [];
    foreach ($iv as $cur) {
        $n = count($merged);
        if ($n > 0 && $cur[0] <= $merged[$n - 1][1]) {
            // overlaps the last block: stretch its end if needed
            $merged[$n - 1][1] = max($merged[$n - 1][1], $cur[1]);
        } else {
            $merged[] = $cur;                      // a gap: start a new block
        }
    }
    return $merged;
}

echo json_encode(mergeIntervals([[1, 3], [8, 10], [2, 6], [15, 18], [17, 20]]));
// [[1,6],[8,10],[15,20]]

JavaScript

// Merge all overlapping [start, end] intervals.
function mergeIntervals(iv) {
  iv = [...iv].sort((a, b) => a[0] - b[0]);        // sort by start
  const merged = [];
  for (const cur of iv) {
    const last = merged[merged.length - 1];
    if (last && cur[0] <= last[1]) {
      // overlaps the last block: stretch its end if needed
      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([[1, 3], [8, 10], [2, 6], [15, 18], [17, 20]])));
// [[1,6],[8,10],[15,20]]

Java

import java.util.*;

public class Main {
    // Merge all overlapping {start, end} intervals.
    static List<int[]> mergeIntervals(int[][] input) {
        int[][] iv = input.clone();
        Arrays.sort(iv, (a, b) -> Integer.compare(a[0], b[0]));   // sort by start
        List<int[]> merged = new ArrayList<>();
        for (int[] cur : iv) {
            int[] last = merged.isEmpty() ? null : merged.get(merged.size() - 1);
            if (last != null && cur[0] <= last[1]) {
                // overlaps the last block: stretch its end if needed
                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) {
        var merged = mergeIntervals(new int[][]{{1, 3}, {8, 10}, {2, 6}, {15, 18}, {17, 20}});
        System.out.println(Arrays.deepToString(merged.toArray()));
        // [[1, 6], [8, 10], [15, 20]]
    }
}

Go

package main

import (
	"cmp"
	"fmt"
	"slices"
)

// mergeIntervals merges all overlapping [start, end] intervals.
func mergeIntervals(input [][2]int) [][2]int {
	iv := slices.Clone(input)
	slices.SortFunc(iv, func(a, b [2]int) int { return cmp.Compare(a[0], b[0]) }) // sort by start
	var merged [][2]int
	for _, cur := range iv {
		n := len(merged)
		if n > 0 && cur[0] <= merged[n-1][1] {
			// overlaps the last block: stretch its end if needed
			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{{1, 3}, {8, 10}, {2, 6}, {15, 18}, {17, 20}}))
	// [[1 6] [8 10] [15 20]]
}

Time: O(n log n) · Extra space: O(n). Sorting costs O(n log n); merging is one pass. The answer list can hold up to n intervals.

Watch out for

  • Not sorting first. Overlapping intervals may then be far apart in the list.
  • Setting the new end to the current interval's end instead of max(lastEnd, end). A long block can swallow a shorter one: 1-10 and 2-3 merge into 1-10.
  • Deciding whether touching intervals (3 and 3) should merge. Here we merge them (<=); read the problem statement.

Quick check

  1. Why do we sort by start first?
    • So the list is shorter
    • To remove duplicates
    • So overlapping intervals sit next to each other
  2. Intervals 1-10 and 2-3 are merged. What is the result?
    • 1-10
    • 1-3
    • 2-10
  3. Time complexity of merging n intervals?
    • O(n)
    • O(n log n)
    • O(n²)