Skip to main content

Heap Sweeps

Trigger: several intervals are live at once and each step serves one. Admit, expire and serve from a min-heap of ends. How the loop works: Heap sweep. Not sure this is your page? Which question is it asking?

No waiting construct​

The heap size is the answer. After EXPIRE, the heap holds exactly the intervals live at this start, so SERVE only reads its size: 253 and 2406 keep the largest size it reaches, 1094 weighs each trip by its passengers and checks the load against the capacity. These three problems live on Line Sweeps, where each has both the line sweep and this heap solution.

Jobs wait for the clock​

The heap holds waiting jobs, and you pop the one to do next. One worker does one job at a time, so each step asks which waiting job goes now.

The intervals wait; the clock moves a day at a time. The heap holds the live intervals by end, and each day pops the one that ends first. In 1834 the clock jumps by each task's length instead, and the heap orders by length.

1353. Maximum Number of Events That Can Be Attended​

1353. Maximum Number of Events That Can Be Attended

LeetCode
Medium

Day-by-Day Min-Heap Sweep

FIG. 1353 MAXIMUM NUMBER OF EVENTS THAT CAN BE ATTENDED● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxEvents(self, events: list[list[int]]) -> int:
waiting = events
heapq.heapify(waiting)
ready = []
day = attended = 0
while waiting or ready:
# ADMIT
while waiting and waiting[0][0] <= day:
start, end = heapq.heappop(waiting)
heapq.heappush(ready, (end, start))
# EXPIRE
while ready and ready[0][0] < day:
heapq.heappop(ready)
# SERVE
if ready:
heapq.heappop(ready)
attended += 1
day += 1
return attended
top ↑

1705. Maximum Number of Eaten Apples​

1705. Maximum Number of Eaten Apples

LeetCode
Medium

Two Heaps: Waiting + Ready

FIG. 1705 MAXIMUM NUMBER OF EATEN APPLES● INTERACTIVE
visualization loads as you reach it
class Solution:
def eatenApples(self, apples: list[int], days: list[int]) -> int:
ready = []
waiting = [(start, start + days[start], apples[start]) for start in range(len(apples))]
day = apples = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] <= day:
start, end, count = heapq.heappop(waiting)
heapq.heappush(ready, (end, start, count))
# EXPIRE
while ready and (ready[0][2] <= 0 or ready[0][0] <= day):
heapq.heappop(ready)
# SERVE
if ready:
end, start, count = heapq.heappop(ready)
if waiting:
heapq.heappush(ready, (end, start, count - 1))
apples += 1
day += 1
else: # when we go beyond len(apples)
apples += min(count, end - day)
day += min(count, end - day)
else:
day += 1
return apples
top ↑

1834. Single-Threaded CPU​

1834. Single-Threaded CPU

LeetCode
Medium

Waiting Heap + Ready Heap

FIG. 1834 SINGLE THREADED CPU● INTERACTIVE
visualization loads as you reach it
class Solution:
def getOrder(self, tasks: list[list[int]]) -> list[int]:
waiting = [(start, proc, idx) for idx, (start, proc) in enumerate(tasks)]
heapq.heapify(waiting)
ready = []
ans = []
time = 0
while waiting or ready:
# ADMIT
while waiting and waiting[0][0] <= time:
start, proc, idx = heapq.heappop(waiting)
heapq.heappush(ready, (proc, idx))
# SERVE
if ready:
proc, idx = heapq.heappop(ready)
time += proc
ans.append(idx)
else:
time = waiting[0][0]
return ans
top ↑

A served item may not run again until its cooldown passes. Keep a max-heap of what is ready, park each served item in a queue until its cooldown ends, and when nothing is ready jump the clock to the next release instead of ticking through the gap.

621. Task Scheduler​

621. Task Scheduler

LeetCode
Medium

Max-Heap + Cooldown Queue

FIG. 621 TASK SCHEDULER● INTERACTIVE
visualization loads as you reach it
class Solution:
def leastInterval(self, tasks: list[str], n: int) -> int:
ready = [i for i in collections.Counter(tasks).values()]
heapq.heapify_max(ready)
waiting = collections.deque()
time = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] <= time:
_, count = waiting.popleft()
heapq.heappush_max(ready, count)
 
# SERVE
if ready:
count = heapq.heappop_max(ready)
if count != 1:
waiting.append((time + n + 1, count - 1))
time += 1
elif waiting:
time = waiting[0][0]
return time
top ↑

767. Reorganize String​

767. Reorganize String

LeetCode
Medium

Max-Heap + Cooldown Heap

FIG. 767 REORGANIZE STRING● INTERACTIVE
visualization loads as you reach it
class Solution:
def reorganizeString(self, s: str) -> str:
ready = [(count, char) for char, count in collections.Counter(s).items()]
heapq.heapify_max(ready)
waiting = []
ans = []
idx = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] <= idx:
idx, count, char = heapq.heappop(waiting)
heapq.heappush_max(ready, (count, char))
# SERVE
if ready:
count, char = heapq.heappop_max(ready)
ans.append(char)
if count != 1:
heapq.heappush(waiting, (idx + 2, count - 1, char))
else:
return ""
idx += 1
return "".join(ans)
top ↑

1054. Distant Barcodes​

1054. Distant Barcodes

LeetCode
Medium

Max-Heap + Cooldown Heap

FIG. 1054 DISTANT BARCODES● INTERACTIVE
visualization loads as you reach it
class Solution:
def rearrangeBarcodes(self, barcodes: list[int]) -> list[int]:
ready = [(count, char) for char, count in collections.Counter(barcodes).items()]
heapq.heapify_max(ready)
waiting = []
ans = []
time = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] <= time:
_, count, char = heapq.heappop(waiting)
heapq.heappush_max(ready, (count, char))
# SERVE
if ready:
count, char = heapq.heappop_max(ready)
ans.append(char)
if count != 1:
heapq.heappush(waiting, (time + 2, count - 1, char))
time += 1
return ans
top ↑

358. Rearrange String k Distance Apart​

358. Rearrange String k Distance Apart

LeetCode
Hard

Max-Heap + Cooldown Heap

FIG. 358 REARRANGE STRING K DISTANCE APART● INTERACTIVE
visualization loads as you reach it
class Solution:
def rearrangeString(self, s: str, k: int) -> str:
ready = [(count, char) for char, count in collections.Counter(s).items()]
heapq.heapify_max(ready)
waiting = []
ans = []
idx = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] <= idx:
_, count, char = heapq.heappop(waiting)
heapq.heappush_max(ready, (count, char))
# SERVE
if ready:
count, char = heapq.heappop_max(ready)
ans.append(char)
if count != 1:
heapq.heappush(waiting, (idx + k, count - 1, char))
else:
return ""
idx += 1
return "".join(ans)
top ↑

1405. Longest Happy String​

1405. Longest Happy String

LeetCode
Medium

Max-Heap + Park After a Pair

FIG. 1405 LONGEST HAPPY STRING● INTERACTIVE
visualization loads as you reach it
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
ready = [(n, ch) for n, ch in ((a, "a"), (b, "b"), (c, "c")) if n]
heapq.heapify_max(ready)
waiting = collections.deque()
ans = []
idx = 0
while ready or waiting:
# EXPIRE
while waiting and waiting[0][0] < idx:
_, count, char = waiting.popleft()
heapq.heappush_max(ready, (count, char))
# LOGIC
if ready:
count, char = heapq.heappop_max(ready)
ans.append(char)
if count > 1:
if ans[-2:] == [char, char]:
waiting.append((idx + 1, count - 1, char))
else:
heapq.heappush_max(ready, (count - 1, char))
else:
break
idx += 1
return "".join(ans)
top ↑

2182. Construct String With Repeat Limit​

2182. Construct String With Repeat Limit

LeetCode
Medium

Max-Heap + Park at the Limit

FIG. 2182 CONSTRUCT STRING WITH REPEAT LIMIT● INTERACTIVE
visualization loads as you reach it
class Solution:
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
ready = [(char, count) for char, count in collections.Counter(s).items()]
heapq.heapify_max(ready)
waiting = []
ans = []
idx = 0
streak = 0
while ready or waiting:
# ADMIT
while waiting and waiting[0][0] < idx:
_, char, count = heapq.heappop(waiting)
heapq.heappush_max(ready, (char, count))
# SERVE
if ready:
char, count = heapq.heappop_max(ready)
streak = streak + 1 if ans and ans[-1] == char else 1
ans.append(char)
if count != 1:
if streak == repeatLimit:
heapq.heappush(waiting, (idx + 1, char, count - 1))
else:
heapq.heappush_max(ready, (char, count - 1))
else:
break
idx += 1
return "".join(ans)
top ↑

Resources wait for arrivals​

The heap holds resources or candidates, and each arrival takes or reads one. Arrivals drive the loop, so each step asks what this arrival gets.

Two heaps: free resources and busy (end, id). The resources wait for the intervals. EXPIRE moves every finished resource back to free, then SERVE hands the arrival the smallest free one. With no free one, 2402 and 1882 delay the arrival to whichever busy one finishes first; 1942 always has a free chair.

1942. The Number of the Smallest Unoccupied Chair​

1942. The Number of the Smallest Unoccupied Chair

LeetCode
Medium

Two Heaps: Ready and Waiting Chairs

FIG. 1942 THE NUMBER OF THE SMALLEST UNOCCUPIED CHAIR● INTERACTIVE
visualization loads as you reach it
class Solution:
def smallestChair(self, times: list[list[int]], targetFriend: int) -> int:
friends = [(start, end, idx) for idx, (start, end) in enumerate(times)]
friends.sort()
ready = list(range(len(times)))
waiting = []
for start, end, idx in friends:
# EXPIRE
while waiting and waiting[0][0] <= start:
_, chair = heapq.heappop(waiting)
heapq.heappush(ready, chair)
# SERVE
chair = heapq.heappop(ready)
heapq.heappush(waiting, (end, chair))
if targetFriend == idx:
return chair
top ↑

2402. Meeting Rooms III​

2402. Meeting Rooms III

LeetCode
Hard

Two Heaps: Ready Rooms and Waiting Rooms

FIG. 2402 MEETING ROOMS III● INTERACTIVE
visualization loads as you reach it
class Solution:
def mostBooked(self, n: int, meetings: list[list[int]]) -> int:
ready = list(range(n))
waiting = []
meetings.sort()
counter = [0] * n
for start, end in meetings:
# EXPIRE
while waiting and waiting[0][0] <= start:
_, room = heapq.heappop(waiting)
heapq.heappush(ready, room)
# SERVE
if ready:
room = heapq.heappop(ready)
heapq.heappush(waiting, (end, room))
else:
time, room = heapq.heappop(waiting)
heapq.heappush(waiting, (time + end - start, room))
counter[room] += 1
return counter.index(max(counter))
top ↑

1882. Process Tasks Using Servers​

1882. Process Tasks Using Servers

LeetCode
Medium

Two Heaps: Free Servers and Busy Servers

FIG. 1882 PROCESS TASKS USING SERVERS● INTERACTIVE
visualization loads as you reach it
class Solution:
def assignTasks(self, servers: list[int], tasks: list[int]) -> list[int]:
ready = [(weight, idx) for idx, weight in enumerate(servers)]
heapq.heapify(ready)
waiting = []
ans = []
for start, duration in enumerate(tasks):
# EXPIRE
while waiting and waiting[0][0] <= start:
_, weight, idx = heapq.heappop(waiting)
heapq.heappush(ready, (weight, idx))
# SERVE
if ready:
weight, idx = heapq.heappop(ready)
heapq.heappush(waiting, (start + duration, weight, idx))
else:
time, weight, idx = heapq.heappop(waiting)
heapq.heappush(waiting, (time + duration, weight, idx))
ans.append(idx)
return ans
top ↑

Read the heap, don't consume it. Each arrival (a query, an event) takes its answer from what is live or what just expired, and SERVE pops nothing: 1851 reads the smallest live interval off the top, 2054 folds every expired event into a running best.

1851. Minimum Interval to Include Each Query​

1851. Minimum Interval to Include Each Query

LeetCode
Hard

Offline Queries Min-Heap Sweep

FIG. 1851 MINIMUM INTERVAL TO INCLUDE EACH QUERY● INTERACTIVE
visualization loads as you reach it
class Solution:
def minInterval(self, intervals: list[list[int]], queries: list[int]) -> list[int]:
queries = sorted((i, idx) for idx, i in enumerate(queries))
ready = []
waiting = intervals
heapq.heapify(waiting)
ans = [None] * len(queries)
for q, idx in queries:
# ADMIT
while waiting and waiting[0][0] <= q:
start, end = heapq.heappop(waiting)
heapq.heappush(ready, (end - start + 1, start, end))
# EXPIRE:
while ready and ready[0][2] < q:
heapq.heappop(ready)
# SERVE
ans[idx] = ready[0][0] if ready else -1
return ans
top ↑

2054. Two Best Non-Overlapping Events​

2054. Two Best Non-Overlapping Events

LeetCode
Medium

Min-Heap Best Finished Value

FIG. 2054 TWO BEST NON OVERLAPPING EVENTS● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxTwoEvents(self, events: list[list[int]]) -> int:
events.sort()
best = ans = 0
ends = []
for start, end, value in events:
# ADMIT
heapq.heappush(ends, (end, value))
# EXPIRE
while ends and ends[0][0] < start:
best = max(best, heapq.heappop(ends)[1])
# SERVE
ans = max(ans, best + value)
return ans
top ↑