intermediate · intervals · sorting · sweep
Combine overlapping bookings
Problem
A shared studio keeps bookings as closed time ranges [start, end]. Combine every group of bookings that overlap or touch (one ends exactly when the next starts) into a single range. Return the combined ranges sorted by start.
In the lab, enter the bookings as one list: start end start end …
Constraints
- 0 ≤ bookings ≤ 16
- 0 ≤ start ≤ end ≤ 99
Examples
[[8, 10], [1, 3], [2, 6], [15, 18], [10, 12]] → [[1, 6], [8, 12], [15, 18]]
Show the solution
Sort by start, then sweep
Once the bookings are sorted by start, a booking can only overlap the most recent combined range: every earlier range ends before that range begins.
Why it is correct
Invariant: after processing the first i sorted bookings, the output holds the combined ranges of those bookings, sorted, pairwise separated by gaps. The next booking starts at or after every earlier start. If it starts ≤ the last range's end, it overlaps or touches that range (and no earlier one, because of the gaps), so extending the end to the maximum keeps the invariant. Otherwise there is a gap between it and everything before it, so it opens a new range.
Complexity
Time O(n log n), extra space O(n) for the sorted copy and the output. Sorting dominates; the sweep is one pass with O(1) work per booking.
For contrast: Repeatedly find any two overlapping ranges and replace them by their union until none overlap; then sort. That costs O(n³) time and O(n) space.
Edge cases
- No bookings: no ranges.
- A booking inside another: the end must not shrink (use max).
- Touching ranges such as [1, 3] and [3, 5] merge.
Common mistakes
- Setting the end to the new booking's end instead of the maximum, which shrinks a range that contains the booking.
- Forgetting to sort, or sorting by end.
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class MergeIntervals
{
/// <summary>Merges closed ranges that overlap or touch; result sorted by start. O(n log n).</summary>
public static List<(int Start, int End)> Merge(IEnumerable<(int Start, int End)> bookings)
{
var sorted = bookings.OrderBy(b => b.Start).ThenBy(b => b.End).ToList();
var merged = new List<(int Start, int End)>();
foreach (var b in sorted)
{
if (merged.Count > 0 && b.Start <= merged[^1].End)
{
merged[^1] = (merged[^1].Start, Math.Max(merged[^1].End, b.End)); // max: b may lie inside
}
else
{
merged.Add(b);
}
}
return merged;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/MergeIntervals.cs
from collections.abc import Iterable
def merge(bookings: Iterable[tuple[int, int]]) -> list[tuple[int, int]]:
"""Merges closed ranges that overlap or touch; result sorted by start. O(n log n)."""
ordered = sorted(bookings)
merged: list[tuple[int, int]] = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end)) # max: the booking may lie inside
else:
merged.append((start, end))
return merged
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/merge_intervals.py
package dev.bekadan.dsa.problems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public final class MergeIntervals {
private MergeIntervals() {
}
/** Merges closed ranges {start, end} that overlap or touch; result sorted by start. O(n log n). */
public static int[][] merge(int[][] bookings) {
int[][] sorted = Arrays.stream(bookings).map(int[]::clone).sorted(Comparator.<int[]>comparingInt(b -> b[0]).thenComparingInt(b -> b[1])).toArray(int[][]::new);
List<int[]> merged = new ArrayList<>();
for (int[] b : sorted) {
if (!merged.isEmpty() && b[0] <= merged.get(merged.size() - 1)[1]) {
int[] last = merged.get(merged.size() - 1);
last[1] = Math.max(last[1], b[1]); // max: the booking may lie inside
} else {
merged.add(b);
}
}
return merged.toArray(new int[0][]);
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/MergeIntervals.java
#pragma once
#include <algorithm>
#include <utility>
#include <vector>
namespace bekadan::dsa::problems {
// Merges closed ranges (start, end) that overlap or touch; result sorted by start. O(n log n).
inline std::vector<std::pair<int, int>> merge_intervals(std::vector<std::pair<int, int>> bookings) {
std::ranges::sort(bookings);
std::vector<std::pair<int, int>> merged;
for (const auto& [start, end] : bookings) {
if (!merged.empty() && start <= merged.back().second) {
merged.back().second = std::max(merged.back().second, end); // max: the booking may lie inside
} else {
merged.emplace_back(start, end);
}
}
return merged;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/merge_intervals.hpp