Sweep Line Algorithm
Software Engineer path · lesson 46 of 99Process interval events sorted by position. Essential for meeting rooms, skyline problems, and rectangle area calculations. Often combined with TreeMap or sorted list.
Times 0–24, like 1-4, 3-5. Up to 12.
6 events from 3 meetings. Sweep left to right.
- 1events = (start, +1) and (end, −1) for every meeting
- 2sort events by time; at a tie, ends (−1) before starts (+1)
- 3rooms = 0
- 4for (time, delta) in events: rooms += delta; best = max(best, rooms)
- 5return best
- Events
- 0 / 6
Rooms in use: 0 · peak 0
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
Meeting rooms
Order the sweep that finds how many rooms a set of meetings needs.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Test your knowledge
In Meeting Rooms II, what do sweep line events represent?
The short version
Imagine a vertical line sweeping across a map from left to right, like a scanner. As it moves, it tracks which intervals it's currently inside. This lets you process all events in sorted order.
In more depth
Events in Motion
Sweep Line converts interval problems into a sequence of point events.
Standard Pattern:
Meeting Rooms Example:
meetings = [[0,30], [5,10], [15,20]]
events = [(0,+1), (5,+1), (10,-1), (15,+1), (20,-1), (30,-1)]
sorted events → sweep → max concurrent = 2 roomsKey Gotchas:
When to reach for this
- Count maximum overlapping intervals
- Find union/intersection of intervals
- 2D geometry with rectangles
- Keywords: 'meeting rooms', 'skyline', 'overlapping intervals'
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required