Sweep line
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A sweep line is an imaginary line that slides along a timeline or a map, stopping only at moments where something starts or ends. You keep a small running count instead of looking at everything at once.
Practical use cases
- Web app: How many meeting rooms do we need?. A workspace booking app has 500 meetings in a day and wants to know the minimum number of rooms. Instead of comparing every pair of meetings, list all starts as plus one and all ends as minus one, sort them by time, and keep a counter. The highest value of the counter is the answer, found in a single pass.
- Web app: Peak load on a server dashboard. An admin chart shows the busiest minute from thousands of user sessions with login and logout times. Sorting those events and sweeping through with a counter reveals peak concurrent users without checking every session against every other. The chart loads quickly because the data is walked through only once, not repeatedly for every session.
- Web app: Overbooking check for a ticketing site. A venue booking site must confirm that no more than 3 workshops run at the same time in a hall. Sweeping through start and end events flags the exact moment the count goes above 3. The warning appears as soon as the booking is saved, so staff can fix the clash before guests arrive.
- System: Map overlays and collisions in games. GIS tools and game engines sweep a line across rectangles to find which ones overlap, so they only compare shapes that the line is touching at the same time. This keeps the work small even with thousands of shapes, because far-apart shapes are never compared with each other.
The story: The Gatekeeper of the Mela
Every year the mohalla held a big mela, and Zoya was the volunteer at the gate. Her job: tell the organizers the exact moment the grounds are most crowded, so they can plan the water stalls.
Her first idea was to take every visitor and compare their stay with every other visitor. With 5000 visitors that meant 25 million comparisons. Her notebook caught fire (almost).
Grandpa Bhaskar gave her a simpler idea from his old railway days. "Don't track visitors. Track the doors. Each arrival is a click on the counter going up. Each departure is a click going down. Write all clicks in time order and just walk through them once, keeping a running number."
Zoya imagined a thin vertical line sweeping across the timetable from morning to night, stopping only at the moments where something changes, and ignoring all the quiet minutes in between. That is the sweep line.
How to spot this problem, and where you need it
You have many things that each start and end (bookings, sessions, shapes) and you need to know the most overlap at one moment, or whether any overlap exists, without comparing every pair.
Signs you need it
- The data is a list of start and end times, and the question includes "at the same time", "overlap", "maximum concurrent" or "minimum rooms".
- Your solution has two nested loops comparing every booking with every other booking.
- The result is fast for 20 bookings but a calendar with 50,000 events makes the page hang.
Where to use it in a project
- A room, seat or equipment booking system that needs to show peak usage or find clashes.
- A server analytics page showing the busiest moment or the number of concurrent users over time.
- A map or drawing feature that finds overlapping rectangles without comparing every pair.
The solution
Turn each item into two events: a start event (plus one) and an end event (minus one). Sort all events by time, putting ends before starts when the times tie if touching is allowed. Walk through them in order, updating a running count. The highest count seen is the peak overlap, and the moment it occurs tells you when the crunch happens.
Payoff: Before: 50,000 events compared pairwise, billions of checks. After: one sort and one pass, done in milliseconds.
Explain it like I am 8
Stand at a bus door with a clicker. Every time a person gets on, click plus. Every time someone gets off, click minus. You never need to know who they are, only the number on your clicker. The biggest number you ever saw is your answer.
How it works, step by step
- Turn each interval into events: a +1 at its start and a −1 at its end.
- Sort the events by time. At a tie, put −1 before +1 if "leave at 5, arrive at 5" should not count as overlapping.
- Sweep: walk through the events in order and update a running count.
- Remember the best: after every event, compare the running count with the record.
- Only the event moments matter, so the sweep never wastes time on quiet moments.
The code in four languages
PHP
<?php
// Find the most guests inside at once. Each visit is [arrive, leave].
function busiest(array $visits): array {
$events = [];
foreach ($visits as [$arrive, $leave]) {
$events[] = [$arrive, 1]; // someone walks in
$events[] = [$leave, -1]; // someone walks out
}
// time first; at the same time, leaving (-1) comes before arriving (+1)
usort($events, fn($a, $b) => [$a[0], $a[1]] <=> [$b[0], $b[1]]);
$inside = 0; $best = 0; $bestTime = 0;
foreach ($events as [$time, $delta]) {
$inside += $delta;
if ($inside > $best) { $best = $inside; $bestTime = $time; }
}
return [$best, $bestTime];
}
[$count, $time] = busiest([[1, 4], [2, 6], [3, 5], [7, 9], [8, 10]]);
echo "Busiest: $count guests at time $time\n"; // 3 guests at time 3JavaScript
// Find the most guests inside at once. Each visit is [arrive, leave].
function busiest(visits) {
const events = [];
for (const [arrive, leave] of visits) {
events.push([arrive, 1]); // someone walks in
events.push([leave, -1]); // someone walks out
}
// time first; at the same time, leaving (-1) comes before arriving (+1)
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let inside = 0, best = 0, bestTime = 0;
for (const [time, delta] of events) {
inside += delta;
if (inside > best) { best = inside; bestTime = time; }
}
return [best, bestTime];
}
const [count, time] = busiest([[1, 4], [2, 6], [3, 5], [7, 9], [8, 10]]);
console.log('Busiest: ' + count + ' guests at time ' + time); // 3 guests at time 3Java
import java.util.*;
public class Main {
// Find the most guests inside at once. Each visit is {arrive, leave}.
static int[] busiest(int[][] visits) {
List<int[]> events = new ArrayList<>();
for (int[] v : visits) {
events.add(new int[]{v[0], 1}); // someone walks in
events.add(new int[]{v[1], -1}); // someone walks out
}
// time first; at the same time, leaving (-1) comes before arriving (+1)
events.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
int inside = 0, best = 0, bestTime = 0;
for (int[] e : events) {
inside += e[1];
if (inside > best) { best = inside; bestTime = e[0]; }
}
return new int[]{best, bestTime};
}
public static void main(String[] args) {
int[] r = busiest(new int[][]{{1, 4}, {2, 6}, {3, 5}, {7, 9}, {8, 10}});
System.out.println("Busiest: " + r[0] + " guests at time " + r[1]); // Busiest: 3 guests at time 3
}
}Go
package main
import (
"fmt"
"sort"
)
type event struct{ time, delta int }
// busiest finds the most guests inside at once. Each visit is [arrive, leave].
func busiest(visits [][2]int) (int, int) {
var events []event
for _, v := range visits {
events = append(events, event{v[0], 1}) // someone walks in
events = append(events, event{v[1], -1}) // someone walks out
}
// time first; at the same time, leaving (-1) comes before arriving (+1)
sort.Slice(events, func(a, b int) bool {
if events[a].time != events[b].time {
return events[a].time < events[b].time
}
return events[a].delta < events[b].delta
})
inside, best, bestTime := 0, 0, 0
for _, e := range events {
inside += e.delta
if inside > best {
best, bestTime = inside, e.time
}
}
return best, bestTime
}
func main() {
count, time := busiest([][2]int{{1, 4}, {2, 6}, {3, 5}, {7, 9}, {8, 10}})
fmt.Printf("Busiest: %d guests at time %d\n", count, time) // Busiest: 3 guests at time 3
}Time: O(n log n) · Extra space: O(n). Sorting the 2n events costs the most; the sweep itself is a single pass.
Watch out for
- Wrong tie order: if one guest leaves at time 5 and another arrives at 5, process the leaving first (unless touching counts as overlap).
- Checking the record before updating the count, so the peak is off by one.
- Comparing every pair of intervals, which is O(n²) and misses the whole point of sweeping.
Quick check
- What does a sweep line algorithm track?
- A running state while moving through sorted events
- Every pair of intervals
- Only the last interval
- Why turn each visit into two events?
- To double the work
- Starts and ends are the only moments the count changes
- To make sorting easier for PHP
- A guest leaves at 5 and another arrives at 5. Which event is processed first (non-overlapping rule)?
- The arrival
- Either, it never matters
- The departure