Heap / Priority Queue Pattern: Template + 163 LeetCode Problems

Keep only the best k elements, or always pull the smallest, in log time.

  • 13 Easy
  • 87 Medium
  • 63 Hard
  • O(log n) per push or pop; O(n log k) for top-k time

What the heap / priority queue pattern is

A heap gives you the smallest element in constant time and maintains that promise through inserts and removals in logarithmic time, without ever fully sorting anything — which is the whole saving. For top-k questions, keep a min-heap capped at size k: push every element, pop whenever the heap grows past k, and the smallest survivor is the kth largest. That is O(n log k) against O(n log n) for a sort, and it works on a stream whose length you do not know. Python's heapq is min-only, so a max-heap is built by pushing negated values, and tuples are compared element by element — which is how you order by a key while carrying a payload, and also how you accidentally crash when the payload is a type that cannot be compared and two keys tie. The two-heap arrangement is worth memorising separately: a max-heap of the lower half against a min-heap of the upper half, rebalanced so their sizes differ by at most one, keeps the median at the tops.

When to use it

  • You need the k largest, k smallest, or k closest — and k is much smaller than n.
  • Elements arrive as a stream and the answer must stay current without re-sorting.
  • A scheduling or simulation loop always processes the currently cheapest or earliest item.
  • Dijkstra's algorithm, or any BFS where edges carry weights.
  • A running median is required, which is the two-heap arrangement.

The heap / priority queue template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 163 problems listed below.

Heap / Priority Queue — Python template
import heapq

def k_largest(nums, k):
    heap = []                       # min-heap holding the k best seen so far
    for value in nums:
        heapq.heappush(heap, value)
        if len(heap) > k:
            heapq.heappop(heap)     # evict the smallest, keeping the top k

    return sorted(heap, reverse=True)   # heap[0] alone is the kth largest

Complexity characteristics

Time
O(log n) per push or pop; O(n log k) for top-k
Auxiliary space
O(n), or O(k) for top-k

A heap is a complete binary tree, so sifting up or down touches one node per level and costs log n. Keeping a capped heap of size k answers top-k in O(n log k) against O(n log n) for a full sort — a real saving when k is small, and the only option at all when the input is a stream of unknown length. Building a heap from an array with heapify is O(n) rather than O(n log n), which is worth knowing when the whole input is available up front.

All 163 heap / priority queue LeetCode problems

Every problem in the library the heap / priority queue pattern applies to, grouped by LeetCode's own difficulty rating. 138 of the 163 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (13)

#ProblemDifficultyTopics
506Relative RanksEasyArray, Sorting, Heap (Priority Queue)
703Kth Largest Element in a StreamEasyTree, Design, Binary Search Tree +3
1046Last Stone WeightEasyArray, Heap (Priority Queue)
1086High FivePremiumEasyArray, Hash Table, Sorting +1
1337The K Weakest Rows in a MatrixEasyArray, Binary Search, Matrix +2
1464Maximum Product of Two Elements in an ArrayEasyArray, Sorting, Heap (Priority Queue)
2099Find Subsequence of Length K With the Largest SumEasyArray, Hash Table, Sorting +1
2231Largest Number After Digit Swaps by ParityEasySorting, Heap (Priority Queue)
2335Minimum Amount of Time to Fill CupsEasyGreedy, Array, Sorting +1
2357Make Array Zero by Subtracting Equal AmountsEasyGreedy, Array, Hash Table +3
2500Delete Greatest Value in Each RowEasyArray, Matrix, Sorting +2
2558Take Gifts From the Richest PileEasyArray, Simulation, Heap (Priority Queue)
2974Minimum Number GameEasyArray, Sorting, Simulation +1

Medium (87)

#ProblemDifficultyTopics
215Kth Largest Element in an ArrayMediumArray, Divide and Conquer, Quickselect +2
264Ugly Number IIMediumHash Table, Math, Dynamic Programming +1
347Top K Frequent ElementsMediumArray, Hash Table, Divide and Conquer +5
355Design TwitterMediumDesign, Hash Table, Linked List +1
373Find K Pairs with Smallest SumsMediumArray, Heap (Priority Queue)
378Kth Smallest Element in a Sorted MatrixMediumArray, Binary Search, Matrix +2
451Sort Characters By FrequencyMediumHash Table, String, Bucket Sort +3
621Task SchedulerMediumGreedy, Array, Hash Table +3
658Find K Closest ElementsMediumArray, Two Pointers, Binary Search +3
659Split Array into Consecutive SubsequencesMediumGreedy, Array, Hash Table +1
692Top K Frequent WordsMediumTrie, Array, Hash Table +5
743Network Delay TimeMediumDepth-First Search, Breadth-First Search, Graph +2
787Cheapest Flights Within K StopsMediumDepth-First Search, Breadth-First Search, Graph +3
973K Closest Points to OriginMediumGeometry, Array, Math +4
1268Search Suggestions SystemMediumTrie, Array, String +3
2336Smallest Number in Infinite SetMediumDesign, Hash Table, Ordered Set +1
2462Total Cost to Hire K WorkersMediumArray, Two Pointers, Simulation +1
2542Maximum Subsequence ScoreMediumGreedy, Array, Sorting +1
253Meeting Rooms IIPremiumMediumGreedy, Array, Two Pointers +3
505The Maze IIPremiumMediumDepth-First Search, Breadth-First Search, Graph +4
767Reorganize StringMediumGreedy, Hash Table, String +3
786K-th Smallest Prime FractionMediumArray, Two Pointers, Binary Search +2
855Exam RoomMediumDesign, Ordered Set, Heap (Priority Queue)
912Sort an ArrayMediumArray, Divide and Conquer, Bucket Sort +5
1054Distant BarcodesMediumGreedy, Array, Hash Table +3
1057Campus BikesPremiumMediumArray, Sorting, Heap (Priority Queue)
1094Car PoolingMediumArray, Prefix Sum, Sorting +2
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1135Connecting Cities With Minimum CostPremiumMediumUnion Find, Graph, Minimum Spanning Tree +1
1167Minimum Cost to Connect SticksPremiumMediumGreedy, Array, Heap (Priority Queue)
1338Reduce Array Size to The HalfMediumGreedy, Array, Hash Table +2
1353Maximum Number of Events That Can Be AttendedMediumGreedy, Array, Sorting +1
1405Longest Happy StringMediumGreedy, String, Heap (Priority Queue)
1424Diagonal Traverse IIMediumArray, Sorting, Heap (Priority Queue)
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumQueue, Array, Ordered Set +3
1488Avoid Flood in The CityMediumGreedy, Array, Hash Table +2
1500Design a File Sharing SystemPremiumMediumDesign, Hash Table, Data Stream +2
1514Path with Maximum ProbabilityMediumGraph, Array, Shortest Path +1
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1642Furthest Building You Can ReachMediumGreedy, Array, Heap (Priority Queue)
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1686Stone Game VIMediumGreedy, Array, Math +3
1696Jump Game VIMediumQueue, Array, Dynamic Programming +2
1705Maximum Number of Eaten ApplesMediumGreedy, Array, Heap (Priority Queue)
1738Find Kth Largest XOR Coordinate ValueMediumBit Manipulation, Array, Divide and Conquer +5
1753Maximum Score From Removing StonesMediumGreedy, Math, Heap (Priority Queue)
1786Number of Restricted Paths From First to Last NodeMediumGraph, Topological Sort, Dynamic Programming +2
1792Maximum Average Pass RatioMediumGreedy, Array, Heap (Priority Queue)
1801Number of Orders in the BacklogMediumArray, Simulation, Heap (Priority Queue)
1810Minimum Path Cost in a Hidden GridPremiumMediumDepth-First Search, Breadth-First Search, Graph +5
1834Single-Threaded CPUMediumArray, Sorting, Heap (Priority Queue)
1845Seat Reservation ManagerMediumDesign, Heap (Priority Queue)
1878Get Biggest Three Rhombus Sums in a GridMediumArray, Math, Matrix +3
1882Process Tasks Using ServersMediumArray, Heap (Priority Queue)
1942The Number of the Smallest Unoccupied ChairMediumArray, Hash Table, Heap (Priority Queue)
1962Remove Stones to Minimize the TotalMediumGreedy, Array, Heap (Priority Queue)
1985Find the Kth Largest Integer in the ArrayMediumArray, String, Divide and Conquer +3
2015Average Height of Buildings in Each SegmentPremiumMediumGreedy, Array, Sorting +1
2034Stock Price FluctuationMediumDesign, Hash Table, Data Stream +2
2054Two Best Non-Overlapping EventsMediumArray, Binary Search, Dynamic Programming +2
2093Minimum Cost to Reach City With DiscountsPremiumMediumGraph, Shortest Path, Heap (Priority Queue)
2146K Highest Ranked Items Within a Price RangeMediumBreadth-First Search, Array, Matrix +2
2182Construct String With Repeat LimitMediumGreedy, Hash Table, String +2
2208Minimum Operations to Halve Array SumMediumGreedy, Array, Heap (Priority Queue)
2233Maximum Product After K IncrementsMediumGreedy, Array, Heap (Priority Queue)
2285Maximum Total Importance of RoadsMediumGreedy, Graph, Sorting +1
2333Minimum Sum of Squared DifferenceMediumGreedy, Array, Binary Search +2
2342Max Sum of a Pair With Equal Sum of DigitsMediumArray, Hash Table, Sorting +1
2343Query Kth Smallest Trimmed NumberMediumArray, String, Divide and Conquer +4
2349Design a Number Container SystemMediumDesign, Hash Table, Ordered Set +1
2353Design a Food Rating SystemMediumDesign, Array, Hash Table +3
2406Divide Intervals Into Minimum Number of GroupsMediumGreedy, Array, Two Pointers +3
2424Longest Uploaded PrefixMediumUnion Find, Design, Binary Indexed Tree +5
2456Most Popular Video CreatorMediumArray, Hash Table, String +2
2473Minimum Cost to Buy ApplesPremiumMediumGraph, Array, Shortest Path +1
2497Maximum Star Sum of a GraphMediumGreedy, Graph, Array +2
2512Reward Top K StudentsMediumArray, Hash Table, String +2
2530Maximal Score After Applying K OperationsMediumGreedy, Array, Heap (Priority Queue)
2593Find Score of an Array After Marking All ElementsMediumArray, Hash Table, Sorting +2
2599Make the Prefix Sum Non-negativePremiumMediumGreedy, Array, Heap (Priority Queue)
2611Mice and CheeseMediumGreedy, Array, Sorting +1
2662Minimum Cost of a Path With Special RoadsMediumGraph, Array, Shortest Path +1
2679Sum in a MatrixMediumArray, Matrix, Sorting +2
2737Find the Closest Marked NodePremiumMediumGraph, Array, Shortest Path +1
2762Continuous SubarraysMediumQueue, Array, Ordered Set +3
2812Find the Safest Path in a GridMediumBreadth-First Search, Union Find, Array +3
2944Minimum Number of Coins for FruitsMediumQueue, Array, Dynamic Programming +2

Hard (63)

#ProblemDifficultyTopics
23Merge k Sorted ListsHardLinked List, Divide and Conquer, Heap (Priority Queue) +1
218The Skyline ProblemHardBinary Indexed Tree, Segment Tree, Array +5
239Sliding Window MaximumHardQueue, Array, Sliding Window +2
295Find Median from Data StreamHardDesign, Two Pointers, Data Stream +2
407Trapping Rain Water IIHardBreadth-First Search, Array, Matrix +1
420Strong Password CheckerHardGreedy, String, Heap (Priority Queue)
480Sliding Window MedianHardArray, Hash Table, Sliding Window +1
502IPOHardGreedy, Array, Sorting +1
630Course Schedule IIIHardGreedy, Array, Sorting +1
632Smallest Range Covering Elements from K ListsHardGreedy, Array, Hash Table +3
675Cut Off Trees for Golf EventHardBreadth-First Search, Array, Matrix +1
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
1851Minimum Interval to Include Each QueryHardArray, Binary Search, Sorting +2
272Closest Binary Search Tree Value IIPremiumHardStack, Tree, Depth-First Search +4
358Rearrange String k Distance ApartPremiumHardGreedy, Hash Table, String +3
499The Maze IIIPremiumHardDepth-First Search, Breadth-First Search, Graph +5
642Design Search Autocomplete SystemPremiumHardDepth-First Search, Design, Trie +4
683K Empty SlotsPremiumHardBinary Indexed Tree, Segment Tree, Queue +5
759Employee Free TimePremiumHardArray, Sorting, Line Sweep +1
857Minimum Cost to Hire K WorkersHardGreedy, Array, Sorting +1
862Shortest Subarray with Sum at Least KHardQueue, Array, Binary Search +4
871Minimum Number of Refueling StopsHardGreedy, Array, Dynamic Programming +1
882Reachable Nodes In Subdivided GraphHardGraph, Shortest Path, Heap (Priority Queue)
1168Optimize Water Distribution in a VillagePremiumHardUnion Find, Graph, Minimum Spanning Tree +1
1172Dinner Plate StacksHardStack, Design, Hash Table +1
1183Maximum Number of OnesPremiumHardGreedy, Math, Sorting +1
1199Minimum Time to Build BlocksPremiumHardGreedy, Array, Math +1
1263Minimum Moves to Move a Box to Their Target LocationHardBreadth-First Search, Array, Matrix +1
1354Construct Target Array With Multiple SumsHardArray, Heap (Priority Queue)
1368Minimum Cost to Make at Least One Valid Path in a GridHardBreadth-First Search, Graph, Array +3
1383Maximum Performance of a TeamHardGreedy, Array, Sorting +1
1388Pizza With 3n SlicesHardGreedy, Array, Dynamic Programming +1
1425Constrained Subsequence SumHardQueue, Array, Dynamic Programming +3
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsHardArray, Binary Search, Matrix +1
1499Max Value of EquationHardQueue, Array, Sliding Window +2
1606Find Servers That Handled Most Number of RequestsHardArray, Ordered Set, Simulation +1
1675Minimize Deviation in ArrayHardGreedy, Array, Ordered Set +1
1687Delivering Boxes from Storage to PortsHardSegment Tree, Queue, Array +4
1776Car Fleet IIHardStack, Array, Math +2
1825Finding MK AverageHardDesign, Queue, Data Stream +2
1912Design Movie Rental SystemHardDesign, Array, Hash Table +2
2102Sequentially Ordinal Rank TrackerHardDesign, Data Stream, Ordered Set +1
2163Minimum Difference in Sums After Removal of ElementsHardArray, Dynamic Programming, Heap (Priority Queue)
2290Minimum Obstacle Removal to Reach CornerHardBreadth-First Search, Graph, Array +3
2344Minimum Deletions to Make Array DivisibleHardArray, Math, Number Theory +2
2386Find the K-Sum of an ArrayHardArray, Sorting, Heap (Priority Queue)
2398Maximum Number of Robots Within BudgetHardQueue, Array, Binary Search +4
2402Meeting Rooms IIIHardArray, Hash Table, Sorting +2
2454Next Greater Element IVHardStack, Array, Binary Search +3
2503Maximum Number of Points From Grid QueriesHardBreadth-First Search, Union Find, Array +4
2532Time to Cross a BridgeHardArray, Simulation, Heap (Priority Queue)
2551Put Marbles in BagsHardGreedy, Array, Sorting +1
2577Minimum Time to Visit a Cell In a GridHardBreadth-First Search, Graph, Array +3
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2642Design Graph With Shortest Path CalculatorHardGraph, Design, Shortest Path +1
2699Modify Graph Edge WeightsHardGraph, Shortest Path, Heap (Priority Queue)
2714Find Shortest Path with K HopsPremiumHardGraph, Shortest Path, Heap (Priority Queue)
2813Maximum Elegance of a K-Length SubsequenceHardStack, Greedy, Array +3
2931Maximum Spending After Buying ItemsHardGreedy, Array, Matrix +2
2940Find Building Where Alice and Bob Can MeetHardStack, Binary Indexed Tree, Segment Tree +4
2959Number of Possible Sets of Closing BranchesHardBit Manipulation, Graph, Enumeration +2
2969Minimum Number of Coins for Fruits IIPremiumHardQueue, Array, Dynamic Programming +2
2973Find Number of Coins to Place in Tree NodesHardTree, Depth-First Search, Dynamic Programming +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

Heap / Priority Queue pattern FAQ

What is the heap / priority queue pattern?

A heap gives you the smallest element in constant time and maintains that promise through inserts and removals in logarithmic time, without ever fully sorting anything — which is the whole saving.

How many LeetCode problems use the heap / priority queue pattern?

This page lists 163 LeetCode problems that the heap / priority queue pattern applies to: 13 Easy, 87 Medium and 63 Hard. 138 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the heap / priority queue pattern?

O(log n) per push or pop; O(n log k) for top-k time and O(n), or O(k) for top-k space. A heap is a complete binary tree, so sifting up or down touches one node per level and costs log n. Keeping a capped heap of size k answers top-k in O(n log k) against O(n log n) for a full sort — a real saving when k is small, and the only option at all when the input is a stream of unknown length. Building a heap from an array with heapify is O(n) rather than O(n log n), which is worth knowing when the whole input is available up front.

When should I use the heap / priority queue pattern in an interview?

You need the k largest, k smallest, or k closest — and k is much smaller than n. Elements arrive as a stream and the answer must stay current without re-sorting.

Which heap / priority queue problem should I start with?

LeetCode 506. Relative Ranks is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to heap / priority queue?

Sorting, Greedy, Breadth-First Search, Binary Search. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.

Meet the heap / priority queue problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer is saying — while staying invisible to screen sharing.