Pattern 14 of 22

Heap / Priority Queue Pattern: Template + 163 LeetCode Problems

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

Easy
13
Medium
87
Hard
63

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.

PythonHeap / Priority Queue 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.

Eyes only

Meet the heap / priority queue problem you did not practise.

In the live round, Stealth Interview reads the 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 says. It's a desktop app for macOS and Windows, invisible to screen sharing.

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)

Easy problems
No.Problem
0506Relative Ranks
0703Kth Largest Element in a Stream
1046Last Stone Weight
1086High FivePremium
1337The K Weakest Rows in a Matrix
1464Maximum Product of Two Elements in an Array
2099Find Subsequence of Length K With the Largest Sum
2231Largest Number After Digit Swaps by Parity
2335Minimum Amount of Time to Fill Cups
2357Make Array Zero by Subtracting Equal Amounts
2500Delete Greatest Value in Each Row
2558Take Gifts From the Richest Pile
2974Minimum Number Game

Medium (87)

Medium problems
No.Problem
0215Kth Largest Element in an Array
0264Ugly Number II
0347Top K Frequent Elements
0355Design Twitter
0373Find K Pairs with Smallest Sums
0378Kth Smallest Element in a Sorted Matrix
0451Sort Characters By Frequency
0621Task Scheduler
0658Find K Closest Elements
0659Split Array into Consecutive Subsequences
0692Top K Frequent Words
0743Network Delay Time
0787Cheapest Flights Within K Stops
0973K Closest Points to Origin
1268Search Suggestions System
2336Smallest Number in Infinite Set
2462Total Cost to Hire K Workers
2542Maximum Subsequence Score
0253Meeting Rooms IIPremium
0505The Maze IIPremium
0767Reorganize String
0786K-th Smallest Prime Fraction
0855Exam Room
0912Sort an Array
1054Distant Barcodes
1057Campus BikesPremium
1094Car Pooling
1102Path With Maximum Minimum ValuePremium
1135Connecting Cities With Minimum CostPremium
1167Minimum Cost to Connect SticksPremium
1338Reduce Array Size to The Half
1353Maximum Number of Events That Can Be Attended
1405Longest Happy String
1424Diagonal Traverse II
1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
1488Avoid Flood in The City
1500Design a File Sharing SystemPremium
1514Path with Maximum Probability
1631Path With Minimum Effort
1642Furthest Building You Can Reach
1648Sell Diminishing-Valued Colored Balls
1686Stone Game VI
1696Jump Game VI
1705Maximum Number of Eaten Apples
1738Find Kth Largest XOR Coordinate Value
1753Maximum Score From Removing Stones
1786Number of Restricted Paths From First to Last Node
1792Maximum Average Pass Ratio
1801Number of Orders in the Backlog
1810Minimum Path Cost in a Hidden GridPremium
1834Single-Threaded CPU
1845Seat Reservation Manager
1878Get Biggest Three Rhombus Sums in a Grid
1882Process Tasks Using Servers
1942The Number of the Smallest Unoccupied Chair
1962Remove Stones to Minimize the Total
1985Find the Kth Largest Integer in the Array
2015Average Height of Buildings in Each SegmentPremium
2034Stock Price Fluctuation
2054Two Best Non-Overlapping Events
2093Minimum Cost to Reach City With DiscountsPremium
2146K Highest Ranked Items Within a Price Range
2182Construct String With Repeat Limit
2208Minimum Operations to Halve Array Sum
2233Maximum Product After K Increments
2285Maximum Total Importance of Roads
2333Minimum Sum of Squared Difference
2342Max Sum of a Pair With Equal Sum of Digits
2343Query Kth Smallest Trimmed Number
2349Design a Number Container System
2353Design a Food Rating System
2406Divide Intervals Into Minimum Number of Groups
2424Longest Uploaded Prefix
2456Most Popular Video Creator
2473Minimum Cost to Buy ApplesPremium
2497Maximum Star Sum of a Graph
2512Reward Top K Students
2530Maximal Score After Applying K Operations
2593Find Score of an Array After Marking All Elements
2599Make the Prefix Sum Non-negativePremium
2611Mice and Cheese
2662Minimum Cost of a Path With Special Roads
2679Sum in a Matrix
2737Find the Closest Marked NodePremium
2762Continuous Subarrays
2812Find the Safest Path in a Grid
2944Minimum Number of Coins for Fruits

Hard (63)

Hard problems
No.Problem
0023Merge k Sorted Lists
0218The Skyline Problem
0239Sliding Window Maximum
0295Find Median from Data Stream
0407Trapping Rain Water II
0420Strong Password Checker
0480Sliding Window Median
0502IPO
0630Course Schedule III
0632Smallest Range Covering Elements from K Lists
0675Cut Off Trees for Golf Event
0778Swim in Rising Water
1851Minimum Interval to Include Each Query
0272Closest Binary Search Tree Value IIPremium
0358Rearrange String k Distance ApartPremium
0499The Maze IIIPremium
0642Design Search Autocomplete SystemPremium
0683K Empty SlotsPremium
0759Employee Free TimePremium
0857Minimum Cost to Hire K Workers
0862Shortest Subarray with Sum at Least K
0871Minimum Number of Refueling Stops
0882Reachable Nodes In Subdivided Graph
1168Optimize Water Distribution in a VillagePremium
1172Dinner Plate Stacks
1183Maximum Number of OnesPremium
1199Minimum Time to Build BlocksPremium
1263Minimum Moves to Move a Box to Their Target Location
1354Construct Target Array With Multiple Sums
1368Minimum Cost to Make at Least One Valid Path in a Grid
1383Maximum Performance of a Team
1388Pizza With 3n Slices
1425Constrained Subsequence Sum
1439Find the Kth Smallest Sum of a Matrix With Sorted Rows
1499Max Value of Equation
1606Find Servers That Handled Most Number of Requests
1675Minimize Deviation in Array
1687Delivering Boxes from Storage to Ports
1776Car Fleet II
1825Finding MK Average
1912Design Movie Rental System
2102Sequentially Ordinal Rank Tracker
2163Minimum Difference in Sums After Removal of Elements
2290Minimum Obstacle Removal to Reach Corner
2344Minimum Deletions to Make Array Divisible
2386Find the K-Sum of an Array
2398Maximum Number of Robots Within Budget
2402Meeting Rooms III
2454Next Greater Element IV
2503Maximum Number of Points From Grid Queries
2532Time to Cross a Bridge
2551Put Marbles in Bags
2577Minimum Time to Visit a Cell In a Grid
2617Minimum Number of Visited Cells in a Grid
2642Design Graph With Shortest Path Calculator
2699Modify Graph Edge Weights
2714Find Shortest Path with K HopsPremium
2813Maximum Elegance of a K-Length Subsequence
2931Maximum Spending After Buying Items
2940Find Building Where Alice and Bob Can Meet
2959Number of Possible Sets of Closing Branches
2969Minimum Number of Coins for Fruits IIPremium
2973Find Number of Coins to Place in Tree Nodes

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.