Introduction
In our previous lesson, we mastered the interval merging pattern, which relies on sorting intervals by their start times and then performing a linear scan to consolidate overlaps. This powerful technique is the foundation for many interval-based problems.
Today, we'll generalize this idea into a more versatile and powerful technique: the sweep line algorithm. Instead of treating intervals as single entities, we will decompose them into a series of events on a timeline (e.g., start and end points). We then "sweep" a line across this timeline, processing events in chronological order to solve the problem. This approach is exceptionally useful for aggregation problems over intervals, such as finding points of maximum overlap or constructing complex geometric shapes.
Your learning goal is to apply this algorithm to two classic interview problems: "Meeting Rooms II" and the much harder "The Skyline Problem." This will give you a framework for tackling a wide range of problems involving events on a timeline, a common theme in Staff-level interviews.
The Core Concept of the Sweep Line Algorithm
Imagine a vertical line sweeping across a 2D plane from left to right. The algorithm processes geometric objects (in our case, intervals) only when the sweep line intersects them. The key insight is that the state we are tracking (e.g., the number of active intervals) only changes at specific "event points"—typically the start and end points of our intervals.

The general process for a sweep line algorithm is:
- Define Events: Deconstruct your input into a set of event points. For an interval
[start, end], this typically means creating two events: one atstartand one atend. - Sort Events: Collect all events and sort them chronologically by their position on the timeline (e.g., the x-coordinate). Handling tie-breakers at this stage is often critical for correctness.
- Sweep and Process: Iterate through the sorted events. At each event, update a data structure that maintains the current state of the sweep line. The maximum or final value of this state is usually the answer.
Let's apply this framework to our first problem.
Application 1: Meeting Rooms II (LeetCode 253)
This problem asks for the minimum number of conference rooms required for a given list of meeting time intervals. This is equivalent to finding the maximum number of concurrent meetings at any single point in time.
Meeting Rooms II - Leetcode 253 - Python
First, let's understand the problem and visualize how overlaps translate to the need for more rooms. This video from NeetCode provides a clear initial explanation.
Watch from 00:18 to 01:36. This section frames the problem as finding the maximum number of overlapping meetings, which is the key insight.
Sweep Line Approach
We can model this using a sweep line.
- Events: A meeting starting is a
+1event. A meeting ending is a-1event. - State: A simple counter,
active_meetings, which tracks the number of meetings happening at the current time. - Goal: Find the maximum value that
active_meetingsreaches during the sweep.
The video below explains a very elegant way to implement this sweep by separating start and end times into two sorted arrays and using a two-pointer technique.
Meeting Rooms II - Leetcode 253 - Python
This segment of the NeetCode video explains the sweep line intuition and demonstrates a clever two-pointer implementation. This is an efficient and common way to solve this problem.
Watch from 01:52 to 08:22. Pay close attention to: How iterating through sorted start and end points simulates the sweep line. The logic: if the next event is a start time, we need a room (increment count). If it's an end time, a room is freed (decrement count). The critical tie-breaking rule: if start[s] == end[e], we process the end event first. This is handled implicitly by the condition start[s] < end[e].
Go Implementation: Two-Pointer Method
This implementation directly follows the two-pointer logic discussed in the video. It's efficient and clean.
import "sort"
func minMeetingRooms(intervals [][]int) int {
if len(intervals) == 0 {
return 0
}
n := len(intervals)
startTimes := make([]int, n)
endTimes := make([]int, n)
for i, interval := range intervals {
startTimes[i] = interval[0]
endTimes[i] = interval[1]
}
sort.Ints(startTimes)
sort.Ints(endTimes)
maxRooms := 0
currentRooms := 0
s, e := 0, 0 // Pointers for startTimes and endTimes
// Iterate through all start times
for s < n {
// If the next start time occurs before the earliest end time,
// we need an additional room.
if startTimes[s] < endTimes[e] {
currentRooms++
s++ // Move to the next start event
} else {
// A meeting has ended, so a room is freed.
// We don't increment currentRooms because the new meeting can take the freed room.
s++ // Move to the next start event
e++ // Move to the next end event
}
if currentRooms > maxRooms {
maxRooms = currentRooms
}
}
return maxRooms
}
Alternative: Map-based Event Tracking
Another common way to implement the sweep line is to use a map to store the change in the number of rooms at each timestamp. This approach can sometimes be cleaner to write, though conceptually it's doing the same thing.
253. Meeting Rooms II - Solution & Explanation
For an alternative perspective, this NeetCode.io article explains the map-based approach and provides a Go implementation.
Read the 'Sweep Line Algorithm' section and review the Go code provided. Notice how it uses a map to store the changes (+1 for start, -1 for end) and then iterates through the sorted keys to calculate the running count of rooms.
For a Staff-level discussion, you should be able to compare these approaches. The two-pointer method is very efficient as it avoids map overhead, while the map-based approach might be more extensible if events were more complex than simple +1/-1 changes. Both are in time due to sorting and in space.
Application 2: The Skyline Problem (LeetCode 218)
This is a significantly more challenging problem and a classic test of your sweep line skills. Here, the state we need to track is not just a count, but the maximum height among all active buildings.
Problem: You are given a list of rectangular buildings [left, right, height]. You need to output the "key points" [x, y] that define the skyline's contour.
218. The Skyline Problem - In-Depth Explanation
First, let's get a solid grasp of the problem. What are the inputs and what do the 'key points' in the output really represent? This AlgoMonster article provides a concise introduction.
Read the 'Problem Description' and 'Intuition' sections. The key idea is that the skyline only changes height at the left or right edges of buildings. This naturally leads to a sweep line approach.
Sweep Line with a Max-Heap
To solve this, we need to know the maximum height of all buildings that are "active" at any given x-coordinate. A simple counter is no longer sufficient. This is a perfect use case for a max-heap (or a data structure that can efficiently query the maximum value, like a balanced binary search tree).
The algorithm is as follows:
- Define Events: Decompose each building
[left, right, height]into two events: a start event(left, -height)and an end event(right, height). We use a negative height for start events as a standard trick to help with sorting and event identification. - Sort Events: Sort the events primarily by their x-coordinate. Tie-breaking is crucial here (more on this below).
- Sweep and Process:
- Initialize a data structure (e.g., a multiset or a frequency map of heights) to keep track of active building heights. Let's call it
active_heights. Initially, it contains just0(for the ground). - Iterate through the sorted events. For each event at coordinate
xwith heighth:- If it's a start event (
his negative), add its positive height(-h)toactive_heights. - If it's an end event (
his positive), removehfromactive_heights.
- If it's a start event (
- After processing all events at a given
x, find the current maximum height inactive_heights. - If this
current_max_heightis different from the previous max height, we have found a new key point:(x, current_max_height). Add it to our result.
- Initialize a data structure (e.g., a multiset or a frequency map of heights) to keep track of active building heights. Let's call it
The following video provides an excellent, detailed walkthrough of this entire process.
Tushar Roy's explanation of the Skyline Problem is a classic for a reason. He masterfully breaks down the complex logic, including the critical tie-breaking rules and the use of a priority queue (or TreeMap).
This is the core of the lesson. Watch from 02:36 to 11:50. Focus on: How buildings are broken down into start and end points. Why a priority queue (or similar structure) is needed to track the max height. The step-by-step processing of events and how skyline points are generated only when the max height changes. The detailed discussion of the three critical tie-breaking rules for sorting events at the same x-coordinate. This is a key detail for a correct solution.
Tie-Breaking Rules Summary
As highlighted in the video, correct sorting is paramount. When two events share the same x-coordinate x:
- Start vs. Start: A taller building's start event
(x, -h_tall)should come before a shorter one's(x, -h_short). - End vs. End: A shorter building's end event
(x, h_short)should come before a taller one's(x, h_tall). - Start vs. End: A start event
(x, -h)must come before an end event(x, h). This prevents creating an unnecessary dip to height 0 between two adjacent buildings.
A clever way to implement all these rules is with a single custom sort comparator or by encoding the event type into the sort key.
Go Implementation: Simulating a Multiset
Go's standard library lacks a native multiset or balanced binary search tree, which are ideal for this problem. In an interview, you would be expected to acknowledge this and propose a viable alternative. A common approach is to use a map to store the frequency of active heights, map[height]count, and then find the maximum key when needed. While finding the max in a map is , which can be slow, for interview purposes, it demonstrates the correct logic. Another option is implementing a heap that supports removals, which is more complex.
Here is a Go implementation using the map-as-a-multiset approach.
import (
"sort"
)
// Event represents a building edge: x-coordinate, height, and type (start/end)
// type: -1 for start, 1 for end
type Event struct {
x, height, eventType int
}
func getSkyline(buildings [][]int) [][]int {
events := make([]Event, 0, len(buildings)*2)
for _, b := range buildings {
// Start event: use negative height for sorting trick
events = append(events, Event{x: b[0], height: -b[2]})
// End event
events = append(events, Event{x: b[1], height: b[2]})
}
// Sort events:
// 1. By x-coordinate.
// 2. For same x, start events come first (due to negative height).
// 3. For two starts, taller comes first. For two ends, shorter comes first.
// The negative/positive height trick handles all this correctly.
sort.Slice(events, func(i, j int) bool {
if events[i].x != events[j].x {
return events[i].x < events[j].x
}
return events[i].height < events[j].height
})
// `heights` is a map used as a frequency map (multiset) of active heights.
// We also use a sorted list of keys to find the max height efficiently.
heights := make(map[int]int)
heights[0] = 1 // Ground
sortedHeights := []int{0}
res := [][]int{}
prevMaxHeight := 0
for _, e := range events {
// Process start event
if e.height < 0 {
h := -e.height
heights[h]++
// If this is a new height, add it to our sorted list
if heights[h] == 1 {
// In a real scenario, this would be a log(N) insertion
// into a balanced BST or sorted list. For this demo,
// we'll append and re-sort.
sortedHeights = append(sortedHeights, h)
sort.Ints(sortedHeights)
}
} else { // Process end event
h := e.height
heights[h]--
// If the count of this height drops to zero, remove it.
if heights[h] == 0 {
delete(heights, h)
// In a real scenario, this would be a log(N) removal.
// We find and remove it from our sorted slice.
for i, val := range sortedHeights {
if val == h {
sortedHeights = append(sortedHeights[:i], sortedHeights[i+1:]...)
break
}
}
}
}
currentMaxHeight := sortedHeights[len(sortedHeights)-1]
if currentMaxHeight != prevMaxHeight {
res = append(res, []int{e.x, currentMaxHeight})
prevMaxHeight = currentMaxHeight
}
}
// Post-processing to merge vertical lines
// If two points have the same x, keep only the last one generated
finalRes := [][]int{}
if len(res) > 0 {
finalRes = append(finalRes, res[0])
for i := 1; i < len(res); i++ {
if res[i][0] == res[i-1][0] {
finalRes[len(finalRes)-1] = res[i]
} else {
finalRes = append(finalRes, res[i])
}
}
}
return finalRes
}
Note: The Go implementation above uses a sorted slice to find the max height, which has non-optimal performance for insertions/deletions. In an interview, you'd explain this is a stand-in for a more appropriate data structure like a balanced binary search tree or a heap with removal support, and discuss the performance implications.
Conclusion
Today, we've explored the sweep line algorithm, a powerful generalization of the interval-based techniques we've seen before. It provides a structured way to solve problems by processing events chronologically along a timeline.
Key Takeaways:
- Event-Based Thinking: The core of the sweep line pattern is to decompose input into discrete events, sort them, and process them in order.
- State Management is Key: The complexity of the problem often lies in the data structure used to maintain state during the sweep. It can be as simple as a counter (
Meeting Rooms II) or as complex as a max-heap or balanced BST (The Skyline Problem). - Sorting is Critical: The correctness of a sweep line algorithm almost always depends on a precise sorting order, especially the tie-breaking rules for events that occur at the same location.
- Complexity: The time complexity is typically dominated by the sorting step, making it , where is the number of events. Each step of the sweep then involves a data structure operation, which is often , where is the number of active items.
In our next lesson, we will pivot from geometric and interval-based problems to the vast world of graphs. We will start with a foundational graph traversal technique, Breadth-First Search (BFS), and see how it can be applied to search through "implicit" graphs and state spaces, as seen in problems like "Word Ladder."