Skip to main content

Heap Problems

Problems for each pattern on Heaps. Read the pattern there first; the heading links back to it.

Top K​

215. Kth Largest Element in an Array, 347. Top K Frequent Elements, 703. Kth Largest Element in a Stream, 973. K Closest Points to Origin. The problem below is worked in full.

1337. The K Weakest Rows in a Matrix​

1337. The K Weakest Rows in a Matrix

LeetCode
Easy

Count Soldiers, Keep K with a Heap

FIG. 1337 THE K WEAKEST ROWS IN A MATRIX● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left_rev(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] > target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] > target:
lo = mid + 1
else:
hi = mid
return lo
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
max_heap = []
for row in range(len(mat)):
soldiers = self.bisect_left_rev(mat[row], 0)
# Put the strength/index pairs into a priority queue.
entry = (-soldiers, -row)
heapq.heappush(max_heap, entry)
if len(max_heap) > k:
heapq.heappop(max_heap)
ans = []
# Pull out and return the indexes of the smallest k entries.
# Don't forget to convert them back to positive numbers!
while max_heap:
ans.append(-heapq.heappop(max_heap)[1])
return ans[::-1] # Reverse, as the indexes are around the wrong way.
top ↑

1005. Maximize Sum Of Array After K Negations​

1005. Maximize Sum Of Array After K Negations

LeetCode
Easy

Min-Heap, Flip the Smallest

FIG. 1005 MAXIMIZE SUM OF ARRAY AFTER K NEGATIONS● INTERACTIVE
visualization loads as you reach it
class Solution:
def largestSumAfterKNegations(self, nums: list[int], k: int) -> int:
heapq.heapify(nums)
for _ in range(k):
x = heapq.heappop(nums)
heapq.heappush(nums, -x)
return sum(nums)
top ↑

2099. Find Subsequence of Length K With the Largest Sum​

2099. Find Subsequence of Length K With the Largest Sum

LeetCode
Easy

Max-Heap of (value, index)

FIG. 2099 FIND SUBSEQUENCE OF LENGTH K WITH THE LARGEST SUM● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxSubsequence(self, nums: list[int], k: int) -> list[int]:
ans = [None] * len(nums)
nums = [(i, idx) for idx, i in enumerate(nums)]
heapq.heapify_max(nums)
for _ in range(k):
x, idx = heapq.heappop_max(nums)
ans[idx] = x
return [i for i in ans if i is not None]
top ↑

1046. Last Stone Weight​

1046. Last Stone Weight

LeetCode
Easy

Smash the Two Heaviest

FIG. 1046 LAST STONE WEIGHT● INTERACTIVE
visualization loads as you reach it
class Solution:
def lastStoneWeight(self, stones: list[int]) -> int:
heapq.heapify_max(stones)
while len(stones) > 1:
y = heapq.heappop_max(stones)
x = heapq.heappop_max(stones)
if x != y:
heapq.heappush_max(stones, y - x)
return stones[0] if stones else 0
top ↑

2558. Take Gifts From the Richest Pile​

2558. Take Gifts From the Richest Pile

LeetCode
Easy

Shrink the Top Pile k Times

FIG. 2558 TAKE GIFTS FROM THE RICHEST PILE● INTERACTIVE
visualization loads as you reach it
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
heapq.heapify_max(gifts)
for _ in range(k):
x = heapq.heappop_max(gifts)
heapq.heappush_max(gifts, math.isqrt(x))
return sum(gifts)
top ↑

1962. Remove Stones to Minimize the Total​

1962. Remove Stones to Minimize the Total

LeetCode
Medium

Halve the Biggest Pile k Times

FIG. 1962 REMOVE STONES TO MINIMIZE THE TOTAL● INTERACTIVE
visualization loads as you reach it
class Solution:
def minStoneSum(self, piles: list[int], k: int) -> int:
heapq.heapify_max(piles)
for _ in range(k):
x = heapq.heappop_max(piles)
heapq.heappush_max(piles, (x - 1) // 2 + 1)
return sum(piles)
top ↑

2530. Maximal Score After Applying K Operations​

2530. Maximal Score After Applying K Operations

LeetCode
Medium

Take the Biggest Element k Times

FIG. 2530 MAXIMAL SCORE AFTER APPLYING K OPERATIONS● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxKelements(self, nums: list[int], k: int) -> int:
heapq.heapify_max(nums)
score = 0
for _ in range(k):
x = heapq.heappop_max(nums)
score += x
heapq.heappush_max(nums, (x - 1) // 3 + 1)
return score
top ↑

2208. Minimum Operations to Halve Array Sum​

2208. Minimum Operations to Halve Array Sum

LeetCode
Medium

Halve the Largest Until Half the Sum Is Gone

FIG. 2208 MINIMUM OPERATIONS TO HALVE ARRAY SUM● INTERACTIVE
visualization loads as you reach it
class Solution:
def halveArray(self, nums: list[int]) -> int:
total = sum(nums)
target = total / 2
heapq.heapify_max(nums)
count = 0
while total > target:
x = heapq.heappop_max(nums) / 2
total -= x
heapq.heappush_max(nums, x)
count += 1
return count
top ↑

1913. Maximum Product Difference Between Two Pairs​

1913. Maximum Product Difference Between Two Pairs

LeetCode
Easy

Two Heaps of Size Two

FIG. 1913 MAXIMUM PRODUCT DIFFERENCE BETWEEN TWO PAIRS HEAPS● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
maxi = []
mini = []
for num in nums:
heapq.heappush(maxi, num)
heapq.heappush_max(mini, num)
if len(maxi) > 2:
heapq.heappop(maxi)
heapq.heappop_max(mini)
return maxi[0] * maxi[1] - mini[0] * mini[1]
top ↑

K-way Merge​

23. Merge k Sorted Lists, 378. Kth Smallest Element in a Sorted Matrix, 632. Smallest Range Covering Elements from K Lists.

Two Heaps​

295. Find Median from Data Stream, 480. Sliding Window Median (add lazy deletion), 502. IPO (one heap of affordable projects by profit, one of locked projects by capital).

Earliest to Finish​

These live with the intervals, on Heap Sweeps, where the loop is worked as admit / expire / serve: 1353. Maximum Number of Events That Can Be Attended, 253. Meeting Rooms II, 1094. Car Pooling.

Window Extremes​

239. Sliding Window Maximum​

239. Sliding Window Maximum

LeetCode
Hard

Sliding Window (Max Heap)

FIG. 239 SLIDING WINDOW MAXIMUM● INTERACTIVE
visualization loads as you reach it
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
left = right = 0
heap = [] # Max heap
result = []
 
while right < n:
# Expansion: Add new elements to the heap
while right < n and right - left < k:
heapq.heappush_max(heap, (nums[right], right))
right += 1
# Logic: Append the current maximum to ans
result.append(heap[0][0])
left += 1
# Shrinking: Ensure the top of the heap is within the current window
while heap and heap[0][1] < left:
heapq.heappop_max(heap)
return result
top ↑

1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit​

1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

LeetCode
Medium

Two Heaps (window min/max)

FIG. 1438 LONGEST CONTINUOUS SUBARRAY WITH ABSOLUTE DIFF LESS THAN OR EQUAL TO LIMIT● INTERACTIVE
visualization loads as you reach it
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
n = len(nums)
left = right = 0
maxi = 0
min_heap = []
max_heap = []
isValid = lambda: abs(min_heap[0][0] - max_heap[0][0]) <= limit
while right < n:
heapq.heappush(min_heap, (nums[right], right))
heapq.heappush_max(max_heap, (nums[right], right))
right += 1
while left < right and not isValid():
while min_heap[0][1] <= left:
heapq.heappop(min_heap)
while max_heap[0][1] <= left:
heapq.heappop_max(max_heap)
left += 1
maxi = max(maxi, right - left)
return maxi
top ↑

Cooldown Scheduling​

This one lives with the intervals, on Heap Sweeps: 621. Task Scheduler.

Greedy with Regret​

630. Course Schedule III, 871. Minimum Number of Refueling Stops, 1642. Furthest Building You Can Reach.

Best-first Enumeration​

373. Find K Pairs with Smallest Sums, 264. Ugly Number II, and 378. Kth Smallest Element in a Sorted Matrix again, seen as a grid whose cells step right and down.

Heaps in Graphs​

743. Network Delay Time, 1584. Min Cost to Connect All Points.