Here's a problem that often comes up in coding interviews. You're given a list of meetings, each with a start time and an end time. Your goal is to find the maximum number of meetings happening at the same time. This is equivalent to finding the minimum number of meeting rooms needed to accommodate all of them.
The time values can be as large as a billion, and there can be a hundred thousand meetings. So checking every moment on the timeline isn't practical, and neither is comparing every pair of meetings.
A technique called line sweep solves this problem in O(n log n) time, using a loop that's just a few lines long.
In this lesson, we'll understand how line sweep works, walk through a complete example, learn how to handle ties, and explore a few common variations you'll encounter in coding interviews.
Let's start by thinking about a straightforward approach.
One option is to go through every time value, from the earliest start to the latest end, and count how many meetings are in progress at each point. But if the times go up to a billion, we could end up taking a billion steps, even if there are only a handful of meetings.
A better approach comes from a simple observation. The number of ongoing meetings changes only when a meeting starts or when a meeting ends. Between these two events, the count stays the same. So the maximum must occur at one of the start times.
We could visit each start time and count how many meetings are active at that moment. That works, but checking each of the n start times takes O(n) time, giving us O(n²) overall.
Line sweep builds on the same observation but eliminates the repeated counting.
Imagine a vertical line moving across the timeline from left to right. As the line moves, it keeps track of useful information, such as the number of meetings currently in progress.
Instead of moving one unit at a time, the line jumps directly to the next point where something changes. We call these points events.
In our problem, each meeting generates two events. The start time adds one to our count, and the end time subtracts one. So for n meetings, we have 2n events.
We sort these events by time and process them in chronological order. At each event, we update the current count and check whether it's greater than the maximum we've seen so far.
That's the core idea behind line sweep: convert the input into events, sort them, and process them while keeping track of the relevant state.
Let's walk through an example with six meetings:
We'll assume that a meeting frees up its room at its end time. So a meeting ending at 5 and another starting at 5 can use the same room.
First, we generate the events. Each meeting contributes a +1 at its start and a -1 at its end, giving us twelve events in total. After sorting, the sweep processes them in this order:
| Time | Event | Change | Count | Max |
|---|---|---|---|---|
| 1 | A starts | +1 | 1 | 1 |
| 2 | B starts | +1 | 2 | 2 |
| 3 | C starts | +1 | 3 | 3 |
| 5 | A ends | -1 | 2 | 3 |
| 5 | C ends | -1 | 1 | 3 |
| 5 | D starts | +1 | 2 | 3 |
| 6 | E starts | +1 | 3 | 3 |
| 7 | B ends | -1 | 2 | 3 |
| 8 | D ends | -1 | 1 | 3 |
| 8 | F starts | +1 | 2 | 3 |
| 9 | E ends | -1 | 1 | 3 |
| 10 | F ends | -1 | 0 | 3 |
Our sweep begins at time 1, where meeting A starts. The count becomes 1. At time 2, B starts, bringing the count to 2. At time 3, C starts, bringing the count to 3. This is our new maximum.
At time 5, three things happen: A ends, C ends, and D starts. We process the two end events first. The count drops to 2, then to 1. Next, D starts, bringing the count back up to 2.
At time 6, E starts, and the count reaches 3 again. At time 7, B ends, bringing the count down to 2. At time 8, D ends and F starts, so the count drops to 1 and then returns to 2. At time 9, E ends, leaving one meeting. Finally, at time 10, F ends, and the count returns to 0.
The highest count we encountered was 3, which means we need a minimum of three meeting rooms.
We can also verify this on the timeline. Meetings A, B, and C overlap between 3 and 5, and there is no point where four meetings are active.
In the previous example, we processed the end events at time 5 before the start event. This ordering is important.
Imagine what would happen if we processed D's start first. The count would temporarily increase from 3 to 4 before dropping as A and C ended. We would incorrectly record a maximum of 4, even though A and C have already finished when D begins.
So when multiple events share the same time, we need a consistent rule for breaking ties. That rule depends on how the problem defines its intervals.
| Interval definition | Do [1, 5] and [5, 8] overlap? | Process first at the same time |
|---|---|---|
| End point excluded, as in the meeting example | No | End events |
| Closed, both endpoints included | Yes | Start events |
If an interval ending at 5 doesn't overlap with another starting at 5, as in our meeting example, process end events before start events.
If the intervals are closed, meaning both endpoints are included, intervals touching at 5 do overlap. In that case, process start events first.
For non-overlapping endpoints, we can also apply all events at the same time before checking the count.
During an interview, make sure to clarify how overlapping endpoints are treated before writing your code.
Now let's translate this idea into code.
We start by creating an empty list of events. For each meeting, we add a pair containing its start time and +1, followed by another pair containing its end time and -1.
Next, we sort the event list. We compare events by their time first, and if the times are equal, by their second value. Since -1 is smaller than +1, end events automatically come before start events at the same time. This takes care of our tie-breaking rule.
Next, we initialize two variables to zero: the current count and the maximum count. We iterate through the sorted events. For each event, we add its value to the current count and update the maximum whenever we find a larger count. Once the sweep is complete, we return the maximum.
Generating the events takes O(n) time. Sorting the 2n events takes O(n log n) time. The sweep visits each event exactly once and performs a constant amount of work, taking O(n) time.
So the overall time complexity is O(n log n), and the space complexity is O(n) for storing the events.
Notice that the running time is independent of how large the time values are. Whether the last meeting ends at 10 or at a billion, we only visit the points where something actually changes.
Events don't always have to add or subtract one. Consider a variation called the car pooling problem.
We have a car with a fixed seating capacity. We're given a list of trips, each specifying the number of passengers, their pickup location, and their drop-off location. The car travels in one direction, and our goal is to determine whether it can complete all the trips without exceeding its capacity.
Each trip generates two events: add the passengers at the pickup location and subtract them at the drop-off location.
Suppose the car has six seats and we have four trips:
| Trip | Passengers | Pickup | Drop-off |
|---|---|---|---|
| 1 | 3 | 1 | 4 |
| 2 | 2 | 2 | 6 |
| 3 | 4 | 4 | 8 |
| 4 | 1 | 6 | 9 |
At location 1, three passengers get in. At location 2, two more get in, bringing the total to 5. At location 4, the first group gets out and the third group gets in. The count drops to 2 and then increases to 6. At location 6, two passengers get out and one gets in, leaving 5. At location 8, four passengers get out, and at location 9, the last passenger gets out.
The maximum number of passengers was 6, which is within the car's capacity, so we return true.
Notice how we handled the tie at location 4. We dropped off passengers before picking up new ones. Had we processed the pickup first, the count would have reached 9, incorrectly suggesting that the car couldn't accommodate all the trips.
In the car pooling problem, the locations are small integers. In the standard version, they range from 0 to 1,000. When the coordinates fall within a small range, we can avoid sorting entirely.
We create an array with one slot for each location, initially filled with zeros. For each trip, we add the number of passengers at the pickup index and subtract it at the drop-off index.
We then iterate through the array from left to right, maintaining a running sum. At each index, this sum represents the number of passengers currently in the car. If it ever exceeds the capacity, we return false.
This technique is called a difference array, and it takes O(n + L) time, where L is the size of the coordinate range. We're performing the same sweep, except the array indices already give us the correct ordering.
But when the coordinates are large, such as time values reaching a billion, the array becomes impractical, and sorting the events is the better approach.
So far, we've only needed to maintain a single number during the sweep. But some problems require us to track more information about the active elements.
For example, suppose we're given a collection of buildings, each with a left edge, a right edge, and a height, and we want to find their combined skyline. At any position, the skyline is determined by the tallest building covering that position.
A simple count is no longer enough. We need to track the heights of all active buildings and efficiently retrieve the maximum height. We can use a sorted map that tracks the frequency of each height, or a max heap that lazily removes buildings that have ended when they reach the top.
Let's consider three buildings. The first spans 1 to 6 with height 4, the second spans 3 to 9 with height 7, and the third spans 5 to 11 with height 5.
| Position | Event | Active heights | Skyline height |
|---|---|---|---|
| 1 | Add 4 | 4 | 4 (rises) |
| 3 | Add 7 | 4, 7 | 7 (rises) |
| 5 | Add 5 | 4, 5, 7 | 7 (no change) |
| 6 | Remove 4 | 5, 7 | 7 (no change) |
| 9 | Remove 7 | 5 | 5 (drops) |
| 11 | Remove 5 | none | 0 (drops) |
At position 1, we add height 4. The skyline rises to 4. At position 3, we add 7, and the skyline rises to 7. At position 5, we add 5, but the tallest building is still 7, so nothing changes. At position 6, we remove 4, and the maximum remains 7. At position 9, we remove 7, and the skyline drops to 5. Finally, at position 11, we remove 5, and the skyline returns to 0.
So the skyline changes at positions 1, 3, 9, and 11.
When multiple buildings start or end at the same position, we process all those events before checking the maximum height. Otherwise, we might record a change that doesn't actually exist.
Using a sorted map or a heap, we can process all the insertions and removals in O(n log n) time. Including sorting, the overall complexity remains O(n log n).
The line sweep technique also extends to two dimensions.
Consider a problem involving rectangles, where we need to calculate the total area covered by them. We can sweep a vertical line from left to right along the x-axis. Each rectangle generates two events: one at its left edge and another at its right edge. During the sweep, we maintain the active ranges along the y-axis.
These problems often require a segment tree to efficiently maintain the total covered length, but the underlying sweep follows the same principles.
So how do you recognize a line sweep problem during a coding interview?
First, look for intervals, ranges, or time periods along a line. Look for questions involving overlaps, such as the maximum number of simultaneous events, whether a resource exceeds its capacity, or how something changes across different positions. Large coordinate values are another strong clue, because visiting every individual point may be impractical.
Once you've identified a potential line sweep problem, think through four things:
Remember, if the coordinate range is small, a difference array can help you avoid sorting altogether.