Greedy · O(n log n)

Interval scheduling and merging

Sort by end time and take every compatible interval, or sort by start and merge overlaps.

The full explanation, derivation and practice are in the lesson Greedy algorithms: interval scheduling and merging intervals.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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