Algorithm · Greedy · O(n log n)

Interval scheduling and merging

Two greedy sweeps after one sort: pick the most non-overlapping intervals by earliest end, or merge overlapping intervals by start.

The full derivation, edge cases and exercises are in the lesson Greedy algorithms: interval scheduling and merging intervals. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

To fit as many intervals as possible, always take the one that ends first among those that start after the last one taken: an exchange argument shows any optimal schedule can be rewritten to start with it. To merge, sort by start and extend the current block while the next interval starts before it ends.

Intervals here are half-open [start, end), so [1, 3) and [3, 5) do not overlap for scheduling but touch, and merge, for the union.

Steps

  1. Select: sort by end; take an interval when its start ≥ the end of the last one taken.
  2. Merge: sort by start; extend the current block while the next start ≤ its end, otherwise start a new block.

Invariants

What holds at every step; the correctness argument rests on these.

  • Select: the taken intervals are pairwise disjoint and the last taken end is as small as possible.
  • Merge: emitted blocks are disjoint, sorted and separated by gaps.

Complexity

Interval scheduling and merging complexity
CaseTimeExtra spaceNotes
Either sweepO(n log n)O(n)The sort dominates; the sweep is O(n).

When to use it

Use it when

  • Booking rooms, calendars, merging time ranges or memory regions.

Avoid it when

  • Intervals have weights and you maximize total weight: that needs dynamic programming.

Step through it

The interactive lab for interval scheduling and merging: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Interval selection and merging in four languages, each checked against one shared fixture (ties on end time, touching half-open intervals, duplicates, nested intervals, empty input) and 500 random instances: the selection is compared with a brute-force maximum over all subsets, the merge with the runs of a covered-unit array.

namespace Bekadan.Dsa.Examples.Greedy;
 
/// <summary>
/// Greedy sweeps over half-open intervals [Start, End): [1, 3) and [3, 5) do not overlap.
/// <see cref="Select"/> returns a maximum set of pairwise non-overlapping intervals
/// (earliest end first); <see cref="Merge"/> returns the disjoint blocks of their union
/// (touching intervals merge). Both sort once: O(n log n) time, O(n) extra space.
/// </summary>
public static class IntervalScheduling
{
    /// <summary>Input indices of the intervals taken, in the order taken.</summary>
    public static List<int> Select(IReadOnlyList<(int Start, int End)> intervals)
    {
        // Sort indices by (end, start, index); the index makes every tie deterministic.
        var order = Enumerable.Range(0, intervals.Count).ToArray();
        Array.Sort(order, (a, b) =>
            (intervals[a].End, intervals[a].Start, a).CompareTo((intervals[b].End, intervals[b].Start, b)));
        var taken = new List<int>();
        int? lastEnd = null;
        foreach (int i in order)
        {
            if (lastEnd is null || intervals[i].Start >= lastEnd)
            {
                taken.Add(i);
                lastEnd = intervals[i].End;
            }
            else
            {
                continue; // overlaps the last interval taken
            }
        }
        return taken;
    }
 
    /// <summary>The disjoint blocks of the union, left to right.</summary>
    public static List<(int Start, int End)> Merge(IReadOnlyList<(int Start, int End)> intervals)
    {
        var sorted = intervals.Select((iv, i) => (iv.Start, iv.End, Index: i)).ToList();
        sorted.Sort();  // tuples compare by start, then end, then index
        var blocks = new List<(int Start, int End)>();
        if (sorted.Count == 0)
            return blocks;
        var (start, end, _) = sorted[0];
        for (int k = 1; k < sorted.Count; k++)
        {
            var next = sorted[k];
            if (next.Start <= end)
            {
                end = Math.Max(end, next.End);
            }
            else
            {
                blocks.Add((start, end));
                (start, end) = (next.Start, next.End);
            }
        }
        blocks.Add((start, end));
        return blocks;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Greedy/IntervalScheduling.cs

"""Greedy sweeps over half-open intervals [start, end): [1, 3) and [3, 5) do not overlap.
 
select() returns a maximum set of pairwise non-overlapping intervals (earliest end
first); merge() returns the disjoint blocks of their union (touching intervals merge).
Both sort once: O(n log n) time, O(n) extra space.
"""
 
Interval = tuple[int, int]
 
 
def select(intervals: list[Interval]) -> list[int]:
    """Input indices of the intervals taken, in the order taken."""
    # Sort indices by (end, start, index); the index makes every tie deterministic.
    order = sorted(range(len(intervals)), key=lambda i: (intervals[i][1], intervals[i][0], i))
    taken: list[int] = []
    last_end: int | None = None
    for i in order:
        start, end = intervals[i]
        if last_end is None or start >= last_end:
            taken.append(i)
            last_end = end
        else:
            continue  # overlaps the last interval taken
    return taken
 
 
def merge(intervals: list[Interval]) -> list[Interval]:
    """The disjoint blocks of the union, left to right."""
    ordered = sorted((s, e, i) for i, (s, e) in enumerate(intervals))  # by start, end, index
    blocks: list[Interval] = []
    if not ordered:
        return blocks
    start, end, _ = ordered[0]
    for next_start, next_end, _ in ordered[1:]:
        if next_start <= end:
            end = max(end, next_end)
        else:
            blocks.append((start, end))
            start, end = next_start, next_end
    blocks.append((start, end))
    return blocks

Tested on CPython 3.14.0 · examples/python/dsa_examples/interval_scheduling.py

package dev.bekadan.dsa.greedy;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
 
/**
 * Greedy sweeps over half-open intervals [start, end): [1, 3) and [3, 5) do not overlap.
 * {@link #select} returns a maximum set of pairwise non-overlapping intervals (earliest end
 * first); {@link #merge} returns the disjoint blocks of their union (touching intervals
 * merge). Both sort once: O(n log n) time, O(n) extra space.
 */
public final class IntervalScheduling {
    private IntervalScheduling() {
    }
 
    /** A half-open interval [start, end). */
    public record Interval(int start, int end) {
    }
 
    /** Input indices of the intervals taken, in the order taken. */
    public static List<Integer> select(List<Interval> intervals) {
        // Sort indices by (end, start, index); the index makes every tie deterministic.
        List<Integer> order = IntStream.range(0, intervals.size()).boxed()
                .sorted(Comparator.<Integer>comparingInt(i -> intervals.get(i).end())
                        .thenComparingInt(i -> intervals.get(i).start())
                        .thenComparingInt(i -> i))
                .toList();
        List<Integer> taken = new ArrayList<>();
        Integer lastEnd = null;
        for (int i : order) {
            Interval iv = intervals.get(i);
            if (lastEnd == null || iv.start() >= lastEnd) {
                taken.add(i);
                lastEnd = iv.end();
            } else {
                continue; // overlaps the last interval taken
            }
        }
        return taken;
    }
 
    /** The disjoint blocks of the union, left to right. */
    public static List<Interval> merge(List<Interval> intervals) {
        // List.sort is stable, so equal (start, end) pairs keep their input order.
        List<Interval> sorted = new ArrayList<>(intervals);
        sorted.sort(Comparator.comparingInt(Interval::start).thenComparingInt(Interval::end));
        List<Interval> blocks = new ArrayList<>();
        if (sorted.isEmpty()) {
            return blocks;
        }
        int start = sorted.get(0).start();
        int end = sorted.get(0).end();
        for (Interval next : sorted.subList(1, sorted.size())) {
            if (next.start() <= end) {
                end = Math.max(end, next.end());
            } else {
                blocks.add(new Interval(start, end));
                start = next.start();
                end = next.end();
            }
        }
        blocks.add(new Interval(start, end));
        return blocks;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/greedy/IntervalScheduling.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <numeric>
#include <optional>
#include <tuple>
#include <vector>
 
namespace bekadan::dsa {
 
// A half-open interval [start, end): [1, 3) and [3, 5) do not overlap.
struct Interval {
    int start;
    int end;
    friend bool operator==(const Interval&, const Interval&) = default;
};
 
// Input indices of a maximum set of pairwise non-overlapping intervals (earliest end
// first), in the order taken. O(n log n) time, O(n) extra space.
inline std::vector<std::size_t> select_intervals(const std::vector<Interval>& intervals) {
    // Sort indices by (end, start, index); the index makes every tie deterministic.
    std::vector<std::size_t> order(intervals.size());
    std::iota(order.begin(), order.end(), std::size_t{0});
    std::sort(order.begin(), order.end(), [&](std::size_t a, std::size_t b) {
        return std::tuple(intervals[a].end, intervals[a].start, a) < std::tuple(intervals[b].end, intervals[b].start, b);
    });
    std::vector<std::size_t> taken;
    std::optional<int> last_end;
    for (const std::size_t i : order) {
        if (!last_end || intervals[i].start >= *last_end) {
            taken.push_back(i);
            last_end = intervals[i].end;
        } else {
            continue;  // overlaps the last interval taken
        }
    }
    return taken;
}
 
// The disjoint blocks of the union, left to right (touching intervals merge).
// O(n log n) time, O(n) extra space.
inline std::vector<Interval> merge_intervals(std::vector<Interval> intervals) {
    // std::sort is not stable, but equal (start, end) pairs are indistinguishable here.
    std::sort(intervals.begin(), intervals.end(), [](const Interval& a, const Interval& b) {
        return std::tie(a.start, a.end) < std::tie(b.start, b.end);
    });
    std::vector<Interval> blocks;
    if (intervals.empty()) return blocks;
    Interval current = intervals.front();
    for (std::size_t k = 1; k < intervals.size(); ++k) {
        const Interval& next = intervals[k];
        if (next.start <= current.end) {
            current.end = std::max(current.end, next.end);
        } else {
            blocks.push_back(current);
            current = next;
        }
    }
    blocks.push_back(current);
    return blocks;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/interval_scheduling.hpp

Learn more

Data structures it uses

Problems, patterns and exercises

References