Skip to main content

Line Sweeps

Trigger: how many are live at once, or the running value at each point. Turn each interval into a +1 at its start and a -1 at its end, sort the events, and read the running total. How the sweep works: Line sweep. Not sure this is your page? Which question is it asking?

The peak​

The line sweep, applied: the running total is how many intervals are active at that instant, and the maximum it ever reaches is the answer whenever the question is "how many at once".

253. Meeting Rooms II, 1094. Car Pooling and 2406. Divide Intervals Into Minimum Number of Groups also have a min-heap solution. It computes the same peak but also knows which intervals are open and which frees up first, so it extends to deciding which one to serve: admit / expire / serve.

253. Meeting Rooms II​

253. Meeting Rooms II

LeetCode
Medium

Line Sweep

FIG. 253 MEETING ROOMS II● INTERACTIVE
visualization loads as you reach it
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
def streamEvents(intervals):
events = []
for start, end in intervals:
events.extend([(start, 1), (end, -1)])
return sorted(events)
 
active = maxi = 0
for point, curr in streamEvents(intervals):
active += curr
maxi = max(maxi, active)
return maxi
top ↑

1094. Car Pooling​

1094. Car Pooling

LeetCode
Medium

Line Sweep

FIG. 1094 CAR POOLING SWEEP● INTERACTIVE
visualization loads as you reach it
class Solution:
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
def streamEvents(intervals):
events = []
for num, start, end in intervals:
events.extend([(start, num), (end, -num)])
return sorted(events)
 
active = 0
for point, curr in streamEvents(trips):
active += curr
if active > capacity:
return False
return True
top ↑

2406. Divide Intervals Into Minimum Number of Groups​

2406. Divide Intervals Into Minimum Number of Groups

LeetCode
Medium

Line Sweep

FIG. 2406 DIVIDE INTERVALS SWEEP● INTERACTIVE
visualization loads as you reach it
class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
def streamEvents(intervals):
line = []
for a, b in intervals:
line.extend([[a, 1], [b + 1, -1]])
return sorted(line)
 
active = maxi = 0
for point, curr in streamEvents(intervals):
active += curr
maxi = max(maxi, active)
return maxi
top ↑

1419. Minimum Number of Frogs Croaking​

1419. Minimum Number of Frogs Croaking

LeetCode
Medium

Line Sweep + Counting Sort

FIG. 1419 MIN FROGS BUCKETS● INTERACTIVE
visualization loads as you reach it
class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
buckets = [0] * (len(croakOfFrogs))
counter = collections.defaultdict(int)
croak = "croak"
maxi = active = 0
for idx, char in enumerate(croakOfFrogs):
if char == "c":
buckets[idx] += 1
elif char == "k":
buckets[idx] -= 1
active += buckets[idx]
counter[char] += 1
maxi = max(maxi, active)
if not (counter["c"] >= counter["r"] >= counter["o"] >= counter["a"] >= counter["k"]):
return -1
return maxi if counter["c"] == counter["k"] else -1
top ↑

1854. Maximum Population Year​

1854. Maximum Population Year

LeetCode
Easy

Line Sweep

FIG. 1854 MAXIMUM POPULATION YEAR SWEEP● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumPopulation(self, logs: List[List[int]]) -> int:
def streamEvents(intervals):
line = []
for start, end in intervals:
line.extend([[start, 1], [end, -1]])
return sorted(line, key=lambda i: i)
 
maxi = [-1, 1930]
active = 0
for point, curr in streamEvents(logs):
active += curr
# print(point, curr)
if maxi[0] < active:
maxi = (active, point)
return maxi[1]
top ↑

2779. Maximum Beauty of an Array After Applying Operation​

2779. Maximum Beauty of an Array After Applying Operation

LeetCode
Medium

Line Sweep

FIG. MAXIMUM BEAUTY OF AN ARRAY AFTER APPLYING OPERATION● INTERACTIVE
visualization loads as you reach it
class Solution:
def maximumBeauty(self, nums: List[int], k: int) -> int:
def streamEvents(interval):
line = []
for i in interval:
line.extend([[i - k, 1], [i + k + 1, -1]])
return sorted(line)
 
active = 0
maxi = 0
for point, curr in streamEvents(nums):
active += curr
maxi = max(maxi, active)
return maxi
top ↑

Every point​

Same +1/-1 events, but the peak is not enough: the running value is needed at every position, at every stretch between event points, or at a set of query points. When the coordinates are small indices this is a difference array; when they are sparse, sort the event points (and the queries) and read the running value as the sweep passes each one.

370. Range Addition​

370. Range Addition

LeetCode
Medium

Line Sweep

FIG. 370 RANGE ADDITION SWEEP● INTERACTIVE
visualization loads as you reach it
class Solution:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
def streamEvents(intervals):
line = []
for start, end, weight in intervals:
line.extend([[start, weight], [end + 1, -weight]])
return sorted(line)
 
res = [0] * (length + 1)
prev = None
active = 0
for point, curr in streamEvents(updates):
start = point if prev is None else prev
for i in range(start, point + 1):
res[i] = active
active += curr
res[point] = active
prev = point
return res[:length]
top ↑

1109. Corporate Flight Bookings​

1109. Corporate Flight Bookings

LeetCode
Medium

Line Sweep + Counting Sort

FIG. 1109 CORPORATE FLIGHT BOOKINGS● INTERACTIVE
visualization loads as you reach it
class Solution:
def corpFlightBookings(self, bookings: list[list[int]], n: int) -> list[int]:
def streamEvents():
line = [0] * (n + 2)
for first, last, seats in bookings:
line[first] += seats
line[last + 1] -= seats
return line[1:-1]
 
ans = []
active = 0
for point, curr in enumerate(streamEvents()):
active += curr
ans.append(active)
return ans
top ↑

2381. Shifting Letters II​

2381. Shifting Letters II

LeetCode
Medium

Line Sweep + Counting Sort

FIG. 2381 SHIFTING LETTERS II● INTERACTIVE
visualization loads as you reach it
class Solution:
def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
buckets = [0] * (len(s) + 1)
for start, end, direction in shifts:
direction = -1 if direction == 0 else 1
buckets[start] += direction
buckets[end + 1] -= direction
ans = []
alphabets = "abcdefghijklmnopqrstuvwxyz"
alphabet_map = {j: i for i, j in enumerate(alphabets)}
active = 0
for point, curr in enumerate(buckets[:-1]):
active += curr
char = alphabets[(alphabet_map[s[point]] + active) % 26]
ans.append(char)
return "".join(ans)
top ↑

2237. Count Positions on Street With Required Brightness​

2237. Count Positions on Street With Required Brightness

LeetCode
Medium

Line Sweep + Counting Sort

FIG. 2237 COUNT POSITIONS ON STREET WITH REQUIRED BRIGHTNESS● INTERACTIVE
visualization loads as you reach it
class Solution:
def meetRequirement(self, n: int, lights: List[List[int]], requirement: List[int]) -> int:
buckets = [0] * (n + 2)
for center, rang in lights:
start = max(0, center - rang)
end = min(n - 1, center + rang)
buckets[start] += 1
buckets[end + 1] -= 1
active = 0
count = 0
for point, curr in enumerate(buckets[:-2]):
active += curr
if active >= requirement[point]:
count += 1
return count
top ↑

1943. Describe the Painting​

1943. Describe the Painting

LeetCode
Medium

Line Sweep

FIG. DESCRIBE THE PAINTING● INTERACTIVE
visualization loads as you reach it
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
def streamEvents(intervals):
line = []
for start, end, weight in intervals:
line.extend([[start, weight], [end, -weight]])
return sorted(line)
 
ans = []
active = 0
prev = None
for point, curr in streamEvents(segments):
if prev and point != prev and active:
ans.append([prev, point, active])
prev = point
active += curr
return ans
top ↑

2251. Number of Flowers in Full Bloom​

2251. Number of Flowers in Full Bloom

LeetCode
Hard

Line Sweep + Sorted Queries

FIG. 2251 NUMBER OF FLOWERS IN FULL BLOOM● INTERACTIVE
visualization loads as you reach it
class Solution:
def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
def streamEvents(interval):
events = []
for start, end in flowers:
events.extend([[start, 1], [end + 1, -1]])
return sorted(events)
 
people_sorted = sorted(people)
active = 0
prev = 0
ans = {}
finder = 0
for point, curr in streamEvents(flowers):
while finder < len(people_sorted) and prev <= people_sorted[finder] < point:
ans[people_sorted[finder]] = active
finder += 1
active += curr
prev = point
return [ans.get(i, 0) for i in people]
top ↑

1450. Number of Students Doing Homework at a Given Time​

1450. Number of Students Doing Homework at a Given Time

LeetCode
Easy

Check Every Interval

FIG. 1450 NUMBER OF STUDENTS DOING HOMEWORK AT A GIVEN TIME● INTERACTIVE
visualization loads as you reach it
class Solution:
def busyStudent(self, startTime: list[int], endTime: list[int], queryTime: int) -> int:
count = 0
for i in range(len(startTime)):
if startTime[i] <= queryTime <= endTime[i]:
count += 1
return count
top ↑

Bookings one at a time​

Keep the +1/-1 events in a sorted map and sweep it on every booking. Bookings arrive one at a time and may overlap, so nothing is merged away. Each booking adds its two events, and the running total over the map says how deep the overlap now goes. When only the depth at one point is needed, two binary searches answer it without a sweep.

For the depth at one point, sort the starts and the ends separately and count: started minus finished is how many are live at t.

countStarted = lambda starts, t: bisect_right(starts, t) # how many have begun by t
countFinished = lambda ends, t: bisect_left(ends, t) # how many are already over
depthAt = lambda starts, ends, t: countStarted(starts, t) - countFinished(ends, t)
5t = 5[1,6][3,7][4,13][9,12]1349startsbisect_right(starts, 5) = 36071122133endsbisect_left(ends, 5) = 0depth = 3 - 0 = 3
At t = 5: three started, none finished.

731. My Calendar II​

731. My Calendar II

LeetCode
Medium

Speculative Event Insert with Revert

FIG. 731 MY CALENDAR II● INTERACTIVE
visualization loads as you reach it
import sortedcontainers
 
 
class MyCalendarTwo:
 
def __init__(self):
self.line = sortedcontainers.SortedDict()
 
def book(self, startTime: int, endTime: int) -> bool:
self.line[startTime] = self.line.get(startTime, 0) + 1
self.line[endTime] = self.line.get(endTime, 0) - 1
active = 0
for point, curr in self.line.items():
active += curr
if active > 2:
self.line[startTime] -= 1
self.line[endTime] += 1
return False
return True
 
 
# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(startTime,endTime)
top ↑

732. My Calendar III​

732. My Calendar III

LeetCode
Hard

Persistent Sweep for the Running Peak

FIG. 732 MY CALENDAR III● INTERACTIVE
visualization loads as you reach it
from sortedcontainers import SortedDict
 
 
class MyCalendarThree:
 
def __init__(self):
self.line = SortedDict()
 
def book(self, startTime: int, endTime: int) -> int:
self.line[startTime] = self.line.get(startTime, 0) + 1
self.line[endTime] = self.line.get(endTime, 0) - 1
active = maxi = 0
for point, curr in self.line.items():
active += curr
maxi = max(maxi, active)
return maxi
 
 
# Your MyCalendarThree object will be instantiated and called as such:
# obj = MyCalendarThree()
# param_1 = obj.book(startTime,endTime)
top ↑