Line sweep + intervals
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
This technique sorts ranges (such as time slots) by their starting point and sweeps from left to right, joining any that touch or overlap. It cleans a messy set of ranges into a tidy list of non-overlapping ones.
Practical use cases
- Web app: Calendar free/busy view. A scheduling page shows a doctor as busy or free. Appointments come in random order with overlaps from rescheduling. Sorting by start time and merging touching slots gives a clean list of busy blocks, and the gaps between them are the free slots to offer. The patient sees a simple list of free times, and the clinic avoids the confusing double entries.
- Web app: Tidying a school timetable import. A teacher uploads a messy CSV of class periods. After sorting and merging overlapping periods, the portal shows one clear block for each stretch, and warns about the overlaps it merged. Teachers get a clean, readable view and a short list of the overlaps that were fixed during the import.
- Web app: Firewall or coupon date ranges. An admin panel stores blocked IP ranges or coupon validity dates that grew organically and overlap. Merging them gives a short clean list that is faster to check on each request and easier for staff to read. The firewall rule list shrinks from hundreds of lines to a few, so every incoming request is checked faster.
- System: Video editors and road works. Timeline editors merge overlapping clips on a track, and road departments merge repair spans on the same road, using exactly this sort-and-sweep idea. Editors and planners see one tidy bar where there used to be a messy stack of pieces.
The story: Raju's Messy Timetable
Raju had hired a cleaner and written down the time slots she could come: 1 to 3, 2 to 6, 8 to 10, 15 to 18 and 17 to 20. He wrote them on the back of a bill in whatever order the cleaner told him.
Then the ice-cream man asked: "When is your stall free?" Raju stared at the scribbles. The slot 2 to 6 overlapped with 1 to 3. And 17 to 20 overlapped with 15 to 18. Which gaps were real?
Mrs. Sharma, who loved timetables, gave him a rule. "First, sort the slots by where they begin. Then walk through them once with one open slot in your hand. If the next one starts before your open slot ends, stretch your slot. If it starts later, close your slot and begin a new one."
Raju did it, and his messy bill became three clean blocks. A line sweeping across the day, stretching or closing one block at a time: that is line sweep on intervals.
How to spot this problem, and where you need it
You have a pile of ranges in random order, many of them overlapping, and you need a clean combined view or the gaps between them.
Signs you need it
- Your data is pairs like [start, end], and you are asked to merge, combine, find gaps or find free slots.
- You are comparing each range with every other range to see if they touch.
- Users see duplicated or overlapping blocks on a calendar, timeline or range list.
Where to use it in a project
- A booking or availability screen that must show one block for each busy stretch.
- Cleaning stored IP, date or price ranges so later lookups against them are simple and quick.
- A timeline view in a video-editing or project-planning tool that merges overlapping clips or tasks.
The solution
Sort all ranges by their start. Keep the current merged range. For each next range, if it starts before or when the current one ends, stretch the current end if needed. If it starts after, close the current range, save it, and start a new one. At the end, save the last one. The gaps between saved ranges are your free time.
Payoff: Before: comparing every pair of 10,000 slots. After: one sort and one pass, and a short clean list.
Explain it like I am 8
Imagine colouring strips on a long ruler with a crayon. Strips that touch or overlap become one long coloured stretch. You just slide along the ruler and keep colouring until you hit a gap, then you lift the crayon.
How it works, step by step
- Sort all intervals by their start.
- Take the first interval as the "open" busy period.
- For each next interval: if its start ≤ open end, they overlap: set
open end = max(open end, its end). - Otherwise there is a gap: close the open period, save it, and open a new one.
- After the last interval, save the final open period. Use
maxbecause a long interval can swallow a short one.
The code in four languages
PHP
<?php
// Merge overlapping [start, end] intervals into clean busy periods.
function mergeIntervals(array $iv): array {
usort($iv, fn($a, $b) => $a[0] <=> $b[0]); // 1. sort by start
$out = [];
foreach ($iv as [$s, $e]) {
$last = count($out) - 1;
if ($last >= 0 && $s <= $out[$last][1]) {
$out[$last][1] = max($out[$last][1], $e); // overlap: stretch the open one
} else {
$out[] = [$s, $e]; // gap: start a new one
}
}
return $out;
}
$slots = [[15, 18], [1, 3], [8, 10], [2, 6], [17, 20]];
foreach (mergeIntervals($slots) as [$s, $e]) echo "$s-$e "; // 1-6 8-10 15-20
echo "\n";JavaScript
// Merge overlapping [start, end] intervals into clean busy periods.
function mergeIntervals(iv) {
iv = iv.slice().sort((a, b) => a[0] - b[0]); // 1. sort by start
const out = [];
for (const [s, e] of iv) {
const last = out[out.length - 1];
if (last && s <= last[1]) {
last[1] = Math.max(last[1], e); // overlap: stretch the open one
} else {
out.push([s, e]); // gap: start a new one
}
}
return out;
}
const slots = [[15, 18], [1, 3], [8, 10], [2, 6], [17, 20]];
console.log(mergeIntervals(slots).map(x => x[0] + '-' + x[1]).join(' ')); // 1-6 8-10 15-20Java
import java.util.*;
public class Main {
// Merge overlapping {start, end} intervals into clean busy periods.
static List<int[]> mergeIntervals(int[][] iv) {
int[][] sorted = iv.clone();
Arrays.sort(sorted, (a, b) -> Integer.compare(a[0], b[0])); // 1. sort by start
List<int[]> out = new ArrayList<>();
for (int[] cur : sorted) {
int[] last = out.isEmpty() ? null : out.get(out.size() - 1);
if (last != null && cur[0] <= last[1]) {
last[1] = Math.max(last[1], cur[1]); // overlap: stretch the open one
} else {
out.add(new int[]{cur[0], cur[1]}); // gap: start a new one
}
}
return out;
}
public static void main(String[] args) {
int[][] slots = {{15, 18}, {1, 3}, {8, 10}, {2, 6}, {17, 20}};
StringBuilder sb = new StringBuilder();
for (int[] p : mergeIntervals(slots)) sb.append(p[0]).append('-').append(p[1]).append(' ');
System.out.println(sb.toString().trim()); // 1-6 8-10 15-20
}
}Go
package main
import (
"fmt"
"sort"
"strings"
)
// mergeIntervals merges overlapping [start, end] intervals into clean busy periods.
func mergeIntervals(iv [][2]int) [][2]int {
sorted := append([][2]int{}, iv...)
sort.Slice(sorted, func(a, b int) bool { return sorted[a][0] < sorted[b][0] }) // 1. sort by start
var out [][2]int
for _, cur := range sorted {
last := len(out) - 1
if last >= 0 && cur[0] <= out[last][1] {
out[last][1] = max(out[last][1], cur[1]) // overlap: stretch the open one
} else {
out = append(out, cur) // gap: start a new one
}
}
return out
}
func main() {
slots := [][2]int{{15, 18}, {1, 3}, {8, 10}, {2, 6}, {17, 20}}
var parts []string
for _, p := range mergeIntervals(slots) {
parts = append(parts, fmt.Sprintf("%d-%d", p[0], p[1]))
}
fmt.Println(strings.Join(parts, " ")) // 1-6 8-10 15-20
}Time: O(n log n) · Extra space: O(n). Sorting dominates. The merge pass looks at each interval exactly once.
Watch out for
- Not sorting first. Without sorting, a late-starting slot can overlap something far back.
- Setting the end to the new interval's end instead of
max. A long interval like 1-10 can swallow 2-3. - Forgetting to push the last open interval after the loop (when using a variable instead of the output list).
Quick check
- What do we sort by before sweeping?
- Start time
- Interval length
- End time only
- Open period 1-6 meets interval 2-4. What is the new open period?
- 1-4
- 1-6
- 2-6
- Open period 1-6 meets interval 8-10. What happens?
- Merge into 1-10
- Throw 8-10 away
- Close 1-6 and start 8-10