Pattern 15 of 22

Greedy Pattern: Template + 346 LeetCode Problems

Take the locally best option every time — when you can prove that never costs you later.

Easy
41
Medium
234
Hard
71

What the greedy pattern is

A greedy algorithm commits to the best-looking option at each step and never reconsiders, which makes it the fastest thing that can possibly work and also the easiest thing to get silently wrong. The hard part is never the code — it is three lines — but the justification, and the tool for that is the exchange argument: assume an optimal solution differs from the greedy one, look at the first place they diverge, and show that swapping in the greedy choice leaves the solution no worse. If that swap holds, greedy is correct; if it does not, the problem is dynamic programming wearing a disguise. Choosing what to be greedy about is usually a sorting decision, and the sort key is where the insight lives: interval scheduling works when you sort by earliest finishing time, because finishing early leaves the maximum room for everything after, and it quietly fails if you sort by start time or by duration instead.

When to use it

  • A local choice can be shown, by an exchange argument, never to rule out an optimal completion.
  • Sorting the input by one well-chosen key makes the right choice obvious at every step.
  • The problem is interval scheduling, jump reachability, or an assignment with a clear ordering.
  • A dynamic programming solution exists but its state collapses to a single running best.

The greedy 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 346 problems listed below.

PythonGreedy template
def max_non_overlapping(intervals):
    intervals.sort(key=lambda pair: pair[1])   # earliest finishing time first
    last_end = float("-inf")
    kept = 0

    for start, finish in intervals:
        if start >= last_end:      # taking it never blocks a better option later
            kept += 1
            last_end = finish

    return kept

Complexity characteristics

Time
O(n log n)dominated by the sort
Auxiliary space
O(1) to O(n)

The greedy pass itself is a single linear scan; the sort that makes the greedy choice correct is what sets the complexity. When no sort is needed — a running maximum, a reachability check — the whole solution is O(n). The space is the sort's, which in Python means O(n) for Timsort's temporary buffer rather than the O(1) an in-place quicksort would suggest.

Eyes only

Meet the greedy 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 346 greedy LeetCode problems

Every problem in the library the greedy pattern applies to, grouped by LeetCode's own difficulty rating. 308 of the 346 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 (41)

Easy problems
No.Problem
0409Longest Palindrome
0455Assign Cookies
0561Array Partition
0605Can Place Flowers
0680Valid Palindrome II
0860Lemonade Change
0942DI String Match
0976Largest Perimeter Triangle
1005Maximize Sum Of Array After K Negations
1013Partition Array Into Three Parts With Equal Sum
1196How Many Apples Can You Put into the BasketPremium
1217Minimum Cost to Move Chips to The Same Position
1221Split a String in Balanced Strings
1323Maximum 69 Number
1403Minimum Subsequence in Non-Increasing Order
1708Largest Subarray Length KPremium
1710Maximum Units on a Truck
1736Latest Time by Replacing Hidden Digits
1827Minimum Operations to Make the Array Increasing
1903Largest Odd Number in String
1974Minimum Time to Type Word Using Special Typewriter
2027Minimum Moves to Convert String
2037Minimum Number of Moves to Seat Everyone
2078Two Furthest Houses With Different Colors
2144Minimum Cost of Buying Candies With Discount
2160Minimum Sum of Four Digit Number After Splitting Digits
2224Minimum Number of Operations to Convert Time
2259Remove Digit From Number to Maximize Result
2335Minimum Amount of Time to Fill Cups
2357Make Array Zero by Subtracting Equal Amounts
2383Minimum Hours of Training to Win a Competition
2389Longest Subsequence With Limited Sum
2566Maximum Difference by Remapping a Digit
2578Split With Minimum Sum
2591Distribute Money to Maximum Children
2600K Items With the Maximum Sum
2656Maximum Sum With Exactly K Elements
2697Lexicographically Smallest Palindrome
2706Buy Two Chocolates
2864Maximum Odd Binary Number
2900Longest Unequal Adjacent Groups Subsequence I

Medium (234)

Medium problems
No.Problem
0011Container With Most Water
0045Jump Game II
0055Jump Game
0122Best Time to Buy and Sell Stock II
0134Gas Station
0179Largest Number
0316Remove Duplicate Letters
0324Wiggle Sort II
0334Increasing Triplet Subsequence
0376Wiggle Subsequence
0397Integer Replacement
0402Remove K Digits
0435Non-overlapping Intervals
0452Minimum Number of Arrows to Burst Balloons
0581Shortest Unsorted Continuous Subarray
0611Valid Triangle Number
0621Task Scheduler
0624Maximum Distance in Arrays
0646Maximum Length of Pair Chain
0649Dota2 Senate
0659Split Array into Consecutive Subsequences
0670Maximum Swap
0678Valid Parenthesis String
0714Best Time to Buy and Sell Stock with Transaction Fee
0738Monotone Increasing Digits
0763Partition Labels
0846Hand of Straights
1899Merge Triplets to Form Target Triplet
2542Maximum Subsequence Score
0253Meeting Rooms IIPremium
0280Wiggle SortPremium
0484Find PermutationPremium
0555Split Concatenated StringsPremium
0625Minimum FactorizationPremium
0767Reorganize String
0769Max Chunks To Make Sorted
0781Rabbits in Forest
0807Max Increase to Keep City Skyline
0826Most Profit Assigning Work
0861Score After Flipping Matrix
0870Advantage Shuffle
0881Boats to Save People
0910Smallest Range II
0921Minimum Add to Make Parentheses Valid
0945Minimum Increment to Make Array Unique
0948Bag of Tokens
0954Array of Doubled Pairs
0955Delete Columns to Make Sorted II
0969Pancake Sorting
0984String Without AAA or BBB
0991Broken Calculator
1007Minimum Domino Rotations For Equal Row
1024Video Stitching
1029Two City Scheduling
1053Previous Permutation With One Swap
1054Distant Barcodes
1055Shortest Way to Form StringPremium
1058Minimize Rounding Error to Meet TargetPremium
1081Smallest Subsequence of Distinct Characters
1090Largest Values From Labels
1130Minimum Cost Tree From Leaf Values
1144Decrease Elements To Make Array Zigzag
1167Minimum Cost to Connect SticksPremium
1247Minimum Swaps to Make Strings Equal
1253Reconstruct a 2-Row Binary Matrix
1262Greatest Sum Divisible by Three
1282Group the People Given the Group Size They Belong To
1296Divide Array in Sets of K Consecutive Numbers
1328Break a Palindrome
1338Reduce Array Size to The Half
1353Maximum Number of Events That Can Be Attended
1382Balance a Binary Search Tree
1386Cinema Seat Allocation
1400Construct K Palindrome Strings
1405Longest Happy String
1414Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
1432Max Difference You Can Get From Changing an Integer
1433Check If a String Can Break Another String
1465Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
1481Least Number of Unique Integers after K Removals
1488Avoid Flood in The City
1509Minimum Difference Between Largest and Smallest Value in Three Moves
1529Minimum Suffix Flips
1536Minimum Swaps to Arrange a Binary Grid
1541Minimum Insertions to Balance a Parentheses String
1546Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
1558Minimum Numbers of Function Calls to Make Target Array
1561Maximum Number of Coins You Can Get
1564Put Boxes Into the Warehouse IPremium
1567Maximum Length of Subarray With Positive Product
1578Minimum Time to Make Rope Colorful
1580Put Boxes Into the Warehouse IIPremium
1589Maximum Sum Obtained of Any Permutation
1605Find Valid Matrix Given Row and Column Sums
1642Furthest Building You Can Reach
1647Minimum Deletions to Make Character Frequencies Unique
1648Sell Diminishing-Valued Colored Balls
1663Smallest String With A Given Numeric Value
1673Find the Most Competitive Subsequence
1686Stone Game VI
1689Partitioning Into Minimum Number Of Deci-Binary Numbers
1702Maximum Binary String After Change
1705Maximum Number of Eaten Apples
1717Maximum Score From Removing Substrings
1727Largest Submatrix With Rearrangements
1733Minimum Number of People to Teach
1753Maximum Score From Removing Stones
1754Largest Merge Of Two Strings
1764Form Array by Concatenating Subarrays of Another Array
1775Equal Sum Arrays With Minimum Number of Operations
1785Minimum Elements to Add to Form a Given Sum
1792Maximum Average Pass Ratio
1794Count Pairs of Equal Substrings With Minimum DifferencePremium
1798Maximum Number of Consecutive Values You Can Make
1802Maximum Value at a Given Index in a Bounded Array
1824Minimum Sideway Jumps
1833Maximum Ice Cream Bars
1838Frequency of the Most Frequent Element
1846Maximum Element After Decreasing and Rearranging
1850Minimum Adjacent Swaps to Reach the Kth Smallest Number
1864Minimum Number of Swaps to Make the Binary String Alternating
1874Minimize Product Sum of Two ArraysPremium
1877Minimize Maximum Pair Sum in Array
1881Maximum Value after Insertion
1921Eliminate Maximum Number of Monsters
1927Sum Game
1936Add Minimum Number of Rungs
1946Largest Number After Mutating Substring
1953Maximum Number of Weeks for Which You Can Work
1962Remove Stones to Minimize the Total
1963Minimum Number of Swaps to Make the String Balanced
1968Array With Elements Not Equal to Average of Neighbors
1969Minimum Non-Zero Product of the Array Elements
1975Maximum Matrix Sum
1989Maximum Number of People That Can Be Caught in TagPremium
1996The Number of Weak Characters in the Game
2007Find Original Array From Doubled Array
2015Average Height of Buildings in Each SegmentPremium
2029Stone Game IX
2038Remove Colored Pieces if Both Neighbors are the Same Color
2064Minimized Maximum of Products Distributed to Any Store
2086Minimum Number of Food Buckets to Feed the Hamsters
2087Minimum Cost Homecoming of a Robot in a Grid
2091Removing Minimum and Maximum From Array
2098Subsequence of Size K With the Largest Even SumPremium
2116Check if a Parentheses String Can Be Valid
2126Destroying Asteroids
2131Longest Palindrome by Concatenating Two Letter Words
2139Minimum Moves to Reach Target Score
2170Minimum Operations to Make the Array Alternating
2171Removing Minimum Number of Magic Beans
2178Maximum Split of Positive Even Integers
2182Construct String With Repeat Limit
2195Append K Integers With Minimal Sum
2202Maximize the Topmost Element After K Moves
2207Maximize Number of Subsequences in a String
2208Minimum Operations to Halve Array Sum
2214Minimum Health to Beat GamePremium
2216Minimum Deletions to Make Array Beautiful
2233Maximum Product After K Increments
2241Design an ATM Machine
2244Minimum Rounds to Complete All Tasks
2268Minimum Number of KeypressesPremium
2271Maximum White Tiles Covered by a Carpet
2279Maximum Bags With Full Capacity of Rocks
2285Maximum Total Importance of Roads
2294Partition Array Such That Maximum Difference Is K
2310Sum of Numbers With Units Digit K
2311Longest Binary Subsequence Less Than or Equal to K
2323Find Minimum Time to Finish All Jobs IIPremium
2333Minimum Sum of Squared Difference
2340Minimum Adjacent Swaps to Make a Valid ArrayPremium
2358Maximum Number of Groups Entering a Competition
2375Construct Smallest Number From DI String
2384Largest Palindromic Number
2405Optimal Partition of String
2406Divide Intervals Into Minimum Number of Groups
2410Maximum Matching of Players With Trainers
2422Merge Operations to Turn Array Into a PalindromePremium
2429Minimize XOR
2434Using a Robot to Print the Lexicographically Smallest String
2436Minimum Split Into Subarrays With GCD Greater Than OnePremium
2439Minimize Maximum of Array
2457Minimum Addition to Make Integer Beautiful
2486Append Characters to String to Make Subsequence
2497Maximum Star Sum of a Graph
2498Frog Jump II
2517Maximum Tastiness of Candy Basket
2522Partition String Into Substrings With Values at Most K
2530Maximal Score After Applying K Operations
2541Minimum Operations to Make Array Equal II
2548Maximum Price to Fill a BagPremium
2554Maximum Number of Integers to Choose From a Range I
2557Maximum Number of Integers to Choose From a Range IIPremium
2560House Robber IV
2567Minimum Score by Changing Two Elements
2571Minimum Operations to Reduce an Integer to 0
2576Find the Maximum Number of Marked Indices
2587Rearrange Array to Maximize Prefix Score
2592Maximize Greatness of an Array
2598Smallest Missing Non-negative Integer After Operations
2599Make the Prefix Sum Non-negativePremium
2601Prime Subtraction Operation
2607Make K-Subarray Sums Equal
2611Mice and Cheese
2616Minimize the Maximum Difference of Pairs
2645Minimum Additions to Make Valid String
2673Make Costs of Paths Equal in a Binary Tree
2680Maximum OR
2708Maximum Strength of a Group
2712Minimum Cost to Make All Characters Equal
2734Lexicographically Smallest String After Substring Operation
2745Construct the Longest New String
2789Largest Element in an Array after Merge Operations
2800Shortest String That Contains Three Strings
2811Check if it is Possible to Split Array
2829Determine the Minimum Sum of a k-avoiding Array
2834Find the Minimum Possible Sum of a Beautiful Array
2844Minimum Operations to Make a Special Number
2847Smallest Number With Given Digit ProductPremium
2856Minimum Array Length After Pair Removals
2870Minimum Number of Operations to Make Array Empty
2871Split Array Into Maximum Number of Subarrays
2892Minimizing Array After Replacing Pairs With Their ProductPremium
2895Minimum Processing Time
2910Minimum Number of Groups to Create a Valid Assignment
2918Minimum Equal Sum of Two Arrays After Replacing Zeros
2938Separate Black and White Balls
2939Maximum Xor Product
2952Minimum Number of Coins to be Added
2957Remove Adjacent Almost-Equal Characters
2966Divide Array Into Arrays With Max Difference
2967Minimum Cost to Make Array Equalindromic
2971Find Polygon With the Largest Perimeter

Hard (71)

Hard problems
No.Problem
0044Wildcard Matching
0135Candy
0321Create Maximum Number
0330Patching Array
0410Split Array Largest Sum
0420Strong Password Checker
0502IPO
0517Super Washing Machines
0630Course Schedule III
0632Smallest Range Covering Elements from K Lists
0358Rearrange String k Distance ApartPremium
0527Word AbbreviationPremium
0757Set Intersection Size At Least Two
0765Couples Holding Hands
0768Max Chunks To Make Sorted II
0857Minimum Cost to Hire K Workers
0871Minimum Number of Refueling Stops
0936Stamping The Sequence
1147Longest Chunked Palindrome Decomposition
1183Maximum Number of OnesPremium
1199Minimum Time to Build BlocksPremium
1326Minimum Number of Taps to Open to Water a Garden
1330Reverse Subarray To Maximize Array Value
1363Largest Multiple of Three
1383Maximum Performance of a Team
1388Pizza With 3n Slices
1402Reducing Dishes
1505Minimum Possible Integer After at Most K Adjacent Swaps On Digits
1520Maximum Number of Non-Overlapping Substrings
1526Minimum Number of Increments on Subarrays to Form a Target Array
1537Get the Maximum Score
1585Check If String Is Transformable With Substring Sort Operations
1665Minimum Initial Energy to Finish Tasks
1671Minimum Number of Removals to Make Mountain Array
1675Minimize Deviation in Array
1703Minimum Adjacent Swaps for K Consecutive Ones
1713Minimum Operations to Make a Subsequence
1739Building Boxes
1788Maximize the Beauty of the GardenPremium
2014Longest Subsequence Repeated k Times
2030Smallest K-Length Subsequence With Occurrences of a Letter
2071Maximum Number of Tasks You Can Assign
2132Stamping the Grid
2136Earliest Possible Day of Full Bloom
2141Maximum Running Time of N Computers
2193Minimum Number of Moves to Make Palindrome
2234Maximum Total Beauty of the Gardens
2263Make Array Non-decreasing or Non-increasingPremium
2350Shortest Impossible Sequence of Rolls
2366Minimum Replacements to Sort the Array
2412Minimum Money Required Before Transactions
2448Minimum Cost to Make Array Equal
2449Minimum Number of Operations to Make Arrays Similar
2459Sort Array by Moving Items to Empty SpacePremium
2472Maximum Number of Non-overlapping Palindrome Substrings
2499Minimum Total Cost to Make Arrays Unequal
2528Maximize the Minimum Powered City
2551Put Marbles in Bags
2561Rearranging Fruits
2573Find the String with LCP
2589Minimum Time to Complete All Tasks
2659Make Array Empty
2663Lexicographically Smallest Beautiful String
2790Maximum Number of Groups With Increasing Length
2813Maximum Elegance of a K-Length Subsequence
2818Apply Operations to Maximize Score
2835Minimum Operations to Form Subsequence With Target Sum
2842Count K-Subsequences of a String With Maximum Beauty
2868The Wording GamePremium
2897Apply Operations on Array to Maximize Sum of Squares
2931Maximum Spending After Buying Items

Greedy pattern FAQ

What is the greedy pattern?

A greedy algorithm commits to the best-looking option at each step and never reconsiders, which makes it the fastest thing that can possibly work and also the easiest thing to get silently wrong.

How many LeetCode problems use the greedy pattern?

This page lists 346 LeetCode problems that the greedy pattern applies to: 41 Easy, 234 Medium and 71 Hard. 308 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the greedy pattern?

O(n log n), dominated by the sort time and O(1) to O(n) space. The greedy pass itself is a single linear scan; the sort that makes the greedy choice correct is what sets the complexity. When no sort is needed — a running maximum, a reachability check — the whole solution is O(n). The space is the sort's, which in Python means O(n) for Timsort's temporary buffer rather than the O(1) an in-place quicksort would suggest.

When should I use the greedy pattern in an interview?

A local choice can be shown, by an exchange argument, never to rule out an optimal completion. Sorting the input by one well-chosen key makes the right choice obvious at every step.

Which greedy problem should I start with?

LeetCode 409. Longest Palindrome 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 greedy?

Sorting, Dynamic Programming, Heap / Priority Queue, Two Pointers. 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.