Greedy Pattern: Template + 346 LeetCode Problems

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

  • 41 Easy
  • 234 Medium
  • 71 Hard
  • O(n log n), dominated by the sort time

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.

Greedy — Python 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.

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)

#ProblemDifficultyTopics
409Longest PalindromeEasyGreedy, Hash Table, String
455Assign CookiesEasyGreedy, Array, Two Pointers +1
561Array PartitionEasyGreedy, Array, Counting Sort +1
605Can Place FlowersEasyGreedy, Array
680Valid Palindrome IIEasyGreedy, Two Pointers, String
860Lemonade ChangeEasyGreedy, Array
942DI String MatchEasyGreedy, Array, Two Pointers +1
976Largest Perimeter TriangleEasyGreedy, Array, Math +1
1005Maximize Sum Of Array After K NegationsEasyGreedy, Array, Sorting
1013Partition Array Into Three Parts With Equal SumEasyGreedy, Array
1196How Many Apples Can You Put into the BasketPremiumEasyGreedy, Array, Sorting
1217Minimum Cost to Move Chips to The Same PositionEasyGreedy, Array, Math
1221Split a String in Balanced StringsEasyGreedy, String, Counting
1323Maximum 69 NumberEasyGreedy, Math
1403Minimum Subsequence in Non-Increasing OrderEasyGreedy, Array, Sorting
1708Largest Subarray Length KPremiumEasyGreedy, Array
1710Maximum Units on a TruckEasyGreedy, Array, Sorting
1736Latest Time by Replacing Hidden DigitsEasyGreedy, String
1827Minimum Operations to Make the Array IncreasingEasyGreedy, Array
1903Largest Odd Number in StringEasyGreedy, Math, String
1974Minimum Time to Type Word Using Special TypewriterEasyGreedy, String
2027Minimum Moves to Convert StringEasyGreedy, String
2037Minimum Number of Moves to Seat EveryoneEasyGreedy, Array, Counting Sort +1
2078Two Furthest Houses With Different ColorsEasyGreedy, Array
2144Minimum Cost of Buying Candies With DiscountEasyGreedy, Array, Sorting
2160Minimum Sum of Four Digit Number After Splitting DigitsEasyGreedy, Math, Sorting
2224Minimum Number of Operations to Convert TimeEasyGreedy, String
2259Remove Digit From Number to Maximize ResultEasyGreedy, String, Enumeration
2335Minimum Amount of Time to Fill CupsEasyGreedy, Array, Sorting +1
2357Make Array Zero by Subtracting Equal AmountsEasyGreedy, Array, Hash Table +3
2383Minimum Hours of Training to Win a CompetitionEasyGreedy, Array
2389Longest Subsequence With Limited SumEasyGreedy, Array, Binary Search +2
2566Maximum Difference by Remapping a DigitEasyGreedy, Math
2578Split With Minimum SumEasyGreedy, Math, Sorting
2591Distribute Money to Maximum ChildrenEasyGreedy, Math
2600K Items With the Maximum SumEasyGreedy, Math
2656Maximum Sum With Exactly K ElementsEasyGreedy, Array
2697Lexicographically Smallest PalindromeEasyGreedy, Two Pointers, String
2706Buy Two ChocolatesEasyGreedy, Array, Sorting
2864Maximum Odd Binary NumberEasyGreedy, Math, String
2900Longest Unequal Adjacent Groups Subsequence IEasyGreedy, Array, String +1

Medium (234)

#ProblemDifficultyTopics
11Container With Most WaterMediumGreedy, Array, Two Pointers
45Jump Game IIMediumGreedy, Array, Dynamic Programming
55Jump GameMediumGreedy, Array, Dynamic Programming
122Best Time to Buy and Sell Stock IIMediumGreedy, Array, Dynamic Programming
134Gas StationMediumGreedy, Array
179Largest NumberMediumGreedy, Array, String +1
316Remove Duplicate LettersMediumStack, Greedy, String +1
324Wiggle Sort IIMediumGreedy, Array, Divide and Conquer +2
334Increasing Triplet SubsequenceMediumGreedy, Array
376Wiggle SubsequenceMediumGreedy, Array, Dynamic Programming
397Integer ReplacementMediumGreedy, Bit Manipulation, Memoization +1
402Remove K DigitsMediumStack, Greedy, String +1
435Non-overlapping IntervalsMediumGreedy, Array, Dynamic Programming +1
452Minimum Number of Arrows to Burst BalloonsMediumGreedy, Array, Sorting
581Shortest Unsorted Continuous SubarrayMediumStack, Greedy, Array +3
611Valid Triangle NumberMediumGreedy, Array, Two Pointers +2
621Task SchedulerMediumGreedy, Array, Hash Table +3
624Maximum Distance in ArraysMediumGreedy, Array
646Maximum Length of Pair ChainMediumGreedy, Array, Dynamic Programming +1
649Dota2 SenateMediumGreedy, Queue, String
659Split Array into Consecutive SubsequencesMediumGreedy, Array, Hash Table +1
670Maximum SwapMediumGreedy, Math
678Valid Parenthesis StringMediumStack, Greedy, String +1
714Best Time to Buy and Sell Stock with Transaction FeeMediumGreedy, Array, Dynamic Programming
738Monotone Increasing DigitsMediumGreedy, Math
763Partition LabelsMediumGreedy, Hash Table, Two Pointers +1
846Hand of StraightsMediumGreedy, Array, Hash Table +1
1899Merge Triplets to Form Target TripletMediumGreedy, Array
2542Maximum Subsequence ScoreMediumGreedy, Array, Sorting +1
253Meeting Rooms IIPremiumMediumGreedy, Array, Two Pointers +3
280Wiggle SortPremiumMediumGreedy, Array, Sorting
484Find PermutationPremiumMediumStack, Greedy, Array +1
555Split Concatenated StringsPremiumMediumGreedy, Array, String
625Minimum FactorizationPremiumMediumGreedy, Math
767Reorganize StringMediumGreedy, Hash Table, String +3
769Max Chunks To Make SortedMediumStack, Greedy, Array +2
781Rabbits in ForestMediumGreedy, Array, Hash Table +1
807Max Increase to Keep City SkylineMediumGreedy, Array, Matrix
826Most Profit Assigning WorkMediumGreedy, Array, Two Pointers +2
861Score After Flipping MatrixMediumGreedy, Bit Manipulation, Array +1
870Advantage ShuffleMediumGreedy, Array, Two Pointers +1
881Boats to Save PeopleMediumGreedy, Array, Two Pointers +1
910Smallest Range IIMediumGreedy, Array, Math +1
921Minimum Add to Make Parentheses ValidMediumStack, Greedy, String
945Minimum Increment to Make Array UniqueMediumGreedy, Array, Counting +1
948Bag of TokensMediumGreedy, Array, Two Pointers +1
954Array of Doubled PairsMediumGreedy, Array, Hash Table +1
955Delete Columns to Make Sorted IIMediumGreedy, Array, String
969Pancake SortingMediumGreedy, Array, Two Pointers +1
984String Without AAA or BBBMediumGreedy, String
991Broken CalculatorMediumGreedy, Math
1007Minimum Domino Rotations For Equal RowMediumGreedy, Array
1024Video StitchingMediumGreedy, Array, Dynamic Programming
1029Two City SchedulingMediumGreedy, Array, Sorting
1053Previous Permutation With One SwapMediumGreedy, Array
1054Distant BarcodesMediumGreedy, Array, Hash Table +3
1055Shortest Way to Form StringPremiumMediumGreedy, Two Pointers, String +1
1058Minimize Rounding Error to Meet TargetPremiumMediumGreedy, Array, Math +2
1081Smallest Subsequence of Distinct CharactersMediumStack, Greedy, String +1
1090Largest Values From LabelsMediumGreedy, Array, Hash Table +2
1130Minimum Cost Tree From Leaf ValuesMediumStack, Greedy, Array +2
1144Decrease Elements To Make Array ZigzagMediumGreedy, Array
1167Minimum Cost to Connect SticksPremiumMediumGreedy, Array, Heap (Priority Queue)
1247Minimum Swaps to Make Strings EqualMediumGreedy, Math, String
1253Reconstruct a 2-Row Binary MatrixMediumGreedy, Array, Matrix
1262Greatest Sum Divisible by ThreeMediumGreedy, Array, Dynamic Programming +1
1282Group the People Given the Group Size They Belong ToMediumGreedy, Array, Hash Table
1296Divide Array in Sets of K Consecutive NumbersMediumGreedy, Array, Hash Table +1
1328Break a PalindromeMediumGreedy, String
1338Reduce Array Size to The HalfMediumGreedy, Array, Hash Table +2
1353Maximum Number of Events That Can Be AttendedMediumGreedy, Array, Sorting +1
1382Balance a Binary Search TreeMediumGreedy, Tree, Depth-First Search +3
1386Cinema Seat AllocationMediumGreedy, Bit Manipulation, Array +1
1400Construct K Palindrome StringsMediumGreedy, Hash Table, String +1
1405Longest Happy StringMediumGreedy, String, Heap (Priority Queue)
1414Find the Minimum Number of Fibonacci Numbers Whose Sum Is KMediumGreedy, Math
1432Max Difference You Can Get From Changing an IntegerMediumGreedy, Math
1433Check If a String Can Break Another StringMediumGreedy, String, Sorting
1465Maximum Area of a Piece of Cake After Horizontal and Vertical CutsMediumGreedy, Array, Sorting
1481Least Number of Unique Integers after K RemovalsMediumGreedy, Array, Hash Table +2
1488Avoid Flood in The CityMediumGreedy, Array, Hash Table +2
1509Minimum Difference Between Largest and Smallest Value in Three MovesMediumGreedy, Array, Sorting
1529Minimum Suffix FlipsMediumGreedy, String
1536Minimum Swaps to Arrange a Binary GridMediumGreedy, Array, Matrix
1541Minimum Insertions to Balance a Parentheses StringMediumStack, Greedy, String
1546Maximum Number of Non-Overlapping Subarrays With Sum Equals TargetMediumGreedy, Array, Hash Table +1
1558Minimum Numbers of Function Calls to Make Target ArrayMediumGreedy, Bit Manipulation, Array
1561Maximum Number of Coins You Can GetMediumGreedy, Array, Math +2
1564Put Boxes Into the Warehouse IPremiumMediumGreedy, Array, Sorting
1567Maximum Length of Subarray With Positive ProductMediumGreedy, Array, Dynamic Programming
1578Minimum Time to Make Rope ColorfulMediumGreedy, Array, String +1
1580Put Boxes Into the Warehouse IIPremiumMediumGreedy, Array, Sorting
1589Maximum Sum Obtained of Any PermutationMediumGreedy, Array, Prefix Sum +1
1605Find Valid Matrix Given Row and Column SumsMediumGreedy, Array, Matrix
1642Furthest Building You Can ReachMediumGreedy, Array, Heap (Priority Queue)
1647Minimum Deletions to Make Character Frequencies UniqueMediumGreedy, Hash Table, String +1
1648Sell Diminishing-Valued Colored BallsMediumGreedy, Array, Math +3
1663Smallest String With A Given Numeric ValueMediumGreedy, String
1673Find the Most Competitive SubsequenceMediumStack, Greedy, Array +1
1686Stone Game VIMediumGreedy, Array, Math +3
1689Partitioning Into Minimum Number Of Deci-Binary NumbersMediumGreedy, String
1702Maximum Binary String After ChangeMediumGreedy, String
1705Maximum Number of Eaten ApplesMediumGreedy, Array, Heap (Priority Queue)
1717Maximum Score From Removing SubstringsMediumStack, Greedy, String
1727Largest Submatrix With RearrangementsMediumGreedy, Array, Matrix +1
1733Minimum Number of People to TeachMediumGreedy, Array, Hash Table
1753Maximum Score From Removing StonesMediumGreedy, Math, Heap (Priority Queue)
1754Largest Merge Of Two StringsMediumGreedy, Two Pointers, String
1764Form Array by Concatenating Subarrays of Another ArrayMediumGreedy, Array, Two Pointers +1
1775Equal Sum Arrays With Minimum Number of OperationsMediumGreedy, Array, Hash Table +1
1785Minimum Elements to Add to Form a Given SumMediumGreedy, Array
1792Maximum Average Pass RatioMediumGreedy, Array, Heap (Priority Queue)
1794Count Pairs of Equal Substrings With Minimum DifferencePremiumMediumGreedy, Hash Table, String
1798Maximum Number of Consecutive Values You Can MakeMediumGreedy, Array, Sorting
1802Maximum Value at a Given Index in a Bounded ArrayMediumGreedy, Math, Binary Search
1824Minimum Sideway JumpsMediumGreedy, Array, Dynamic Programming
1833Maximum Ice Cream BarsMediumGreedy, Array, Counting Sort +1
1838Frequency of the Most Frequent ElementMediumGreedy, Array, Binary Search +3
1846Maximum Element After Decreasing and RearrangingMediumGreedy, Array, Sorting
1850Minimum Adjacent Swaps to Reach the Kth Smallest NumberMediumGreedy, Two Pointers, String
1864Minimum Number of Swaps to Make the Binary String AlternatingMediumGreedy, String
1874Minimize Product Sum of Two ArraysPremiumMediumGreedy, Array, Sorting
1877Minimize Maximum Pair Sum in ArrayMediumGreedy, Array, Two Pointers +1
1881Maximum Value after InsertionMediumGreedy, String
1921Eliminate Maximum Number of MonstersMediumGreedy, Array, Sorting
1927Sum GameMediumGreedy, Math, String +1
1936Add Minimum Number of RungsMediumGreedy, Array
1946Largest Number After Mutating SubstringMediumGreedy, Array, String
1953Maximum Number of Weeks for Which You Can WorkMediumGreedy, Array
1962Remove Stones to Minimize the TotalMediumGreedy, Array, Heap (Priority Queue)
1963Minimum Number of Swaps to Make the String BalancedMediumStack, Greedy, Two Pointers +1
1968Array With Elements Not Equal to Average of NeighborsMediumGreedy, Array, Sorting
1969Minimum Non-Zero Product of the Array ElementsMediumGreedy, Recursion, Math
1975Maximum Matrix SumMediumGreedy, Array, Matrix
1989Maximum Number of People That Can Be Caught in TagPremiumMediumGreedy, Array
1996The Number of Weak Characters in the GameMediumStack, Greedy, Array +2
2007Find Original Array From Doubled ArrayMediumGreedy, Array, Hash Table +1
2015Average Height of Buildings in Each SegmentPremiumMediumGreedy, Array, Sorting +1
2029Stone Game IXMediumGreedy, Array, Math +2
2038Remove Colored Pieces if Both Neighbors are the Same ColorMediumGreedy, Math, String +1
2064Minimized Maximum of Products Distributed to Any StoreMediumGreedy, Array, Binary Search
2086Minimum Number of Food Buckets to Feed the HamstersMediumGreedy, String, Dynamic Programming
2087Minimum Cost Homecoming of a Robot in a GridMediumGreedy, Array
2091Removing Minimum and Maximum From ArrayMediumGreedy, Array
2098Subsequence of Size K With the Largest Even SumPremiumMediumGreedy, Array, Sorting
2116Check if a Parentheses String Can Be ValidMediumStack, Greedy, String
2126Destroying AsteroidsMediumGreedy, Array, Sorting
2131Longest Palindrome by Concatenating Two Letter WordsMediumGreedy, Array, Hash Table +2
2139Minimum Moves to Reach Target ScoreMediumGreedy, Math
2170Minimum Operations to Make the Array AlternatingMediumGreedy, Array, Hash Table +1
2171Removing Minimum Number of Magic BeansMediumGreedy, Array, Enumeration +2
2178Maximum Split of Positive Even IntegersMediumGreedy, Math, Backtracking
2182Construct String With Repeat LimitMediumGreedy, Hash Table, String +2
2195Append K Integers With Minimal SumMediumGreedy, Array, Math +1
2202Maximize the Topmost Element After K MovesMediumGreedy, Array
2207Maximize Number of Subsequences in a StringMediumGreedy, String, Prefix Sum
2208Minimum Operations to Halve Array SumMediumGreedy, Array, Heap (Priority Queue)
2214Minimum Health to Beat GamePremiumMediumGreedy, Array
2216Minimum Deletions to Make Array BeautifulMediumStack, Greedy, Array
2233Maximum Product After K IncrementsMediumGreedy, Array, Heap (Priority Queue)
2241Design an ATM MachineMediumGreedy, Design, Array
2244Minimum Rounds to Complete All TasksMediumGreedy, Array, Hash Table +1
2268Minimum Number of KeypressesPremiumMediumGreedy, Hash Table, String +2
2271Maximum White Tiles Covered by a CarpetMediumGreedy, Array, Binary Search +3
2279Maximum Bags With Full Capacity of RocksMediumGreedy, Array, Sorting
2285Maximum Total Importance of RoadsMediumGreedy, Graph, Sorting +1
2294Partition Array Such That Maximum Difference Is KMediumGreedy, Array, Sorting
2310Sum of Numbers With Units Digit KMediumGreedy, Math, Dynamic Programming +1
2311Longest Binary Subsequence Less Than or Equal to KMediumGreedy, Memoization, String +1
2323Find Minimum Time to Finish All Jobs IIPremiumMediumGreedy, Array, Sorting
2333Minimum Sum of Squared DifferenceMediumGreedy, Array, Binary Search +2
2340Minimum Adjacent Swaps to Make a Valid ArrayPremiumMediumGreedy, Array
2358Maximum Number of Groups Entering a CompetitionMediumGreedy, Array, Math +1
2375Construct Smallest Number From DI StringMediumStack, Greedy, String +1
2384Largest Palindromic NumberMediumGreedy, Hash Table, String +1
2405Optimal Partition of StringMediumGreedy, Hash Table, String
2406Divide Intervals Into Minimum Number of GroupsMediumGreedy, Array, Two Pointers +3
2410Maximum Matching of Players With TrainersMediumGreedy, Array, Two Pointers +1
2422Merge Operations to Turn Array Into a PalindromePremiumMediumGreedy, Array, Two Pointers
2429Minimize XORMediumGreedy, Bit Manipulation
2434Using a Robot to Print the Lexicographically Smallest StringMediumStack, Greedy, Hash Table +1
2436Minimum Split Into Subarrays With GCD Greater Than OnePremiumMediumGreedy, Array, Math +2
2439Minimize Maximum of ArrayMediumGreedy, Array, Binary Search +2
2457Minimum Addition to Make Integer BeautifulMediumGreedy, Math
2486Append Characters to String to Make SubsequenceMediumGreedy, Two Pointers, String
2497Maximum Star Sum of a GraphMediumGreedy, Graph, Array +2
2498Frog Jump IIMediumGreedy, Array, Binary Search
2517Maximum Tastiness of Candy BasketMediumGreedy, Array, Binary Search +1
2522Partition String Into Substrings With Values at Most KMediumGreedy, String, Dynamic Programming
2530Maximal Score After Applying K OperationsMediumGreedy, Array, Heap (Priority Queue)
2541Minimum Operations to Make Array Equal IIMediumGreedy, Array, Math
2548Maximum Price to Fill a BagPremiumMediumGreedy, Array, Sorting
2554Maximum Number of Integers to Choose From a Range IMediumGreedy, Array, Hash Table +2
2557Maximum Number of Integers to Choose From a Range IIPremiumMediumGreedy, Array, Binary Search +1
2560House Robber IVMediumGreedy, Array, Binary Search +1
2567Minimum Score by Changing Two ElementsMediumGreedy, Array, Sorting
2571Minimum Operations to Reduce an Integer to 0MediumGreedy, Bit Manipulation, Dynamic Programming
2576Find the Maximum Number of Marked IndicesMediumGreedy, Array, Two Pointers +2
2587Rearrange Array to Maximize Prefix ScoreMediumGreedy, Array, Prefix Sum +1
2592Maximize Greatness of an ArrayMediumGreedy, Array, Two Pointers +1
2598Smallest Missing Non-negative Integer After OperationsMediumGreedy, Array, Hash Table +1
2599Make the Prefix Sum Non-negativePremiumMediumGreedy, Array, Heap (Priority Queue)
2601Prime Subtraction OperationMediumGreedy, Array, Math +2
2607Make K-Subarray Sums EqualMediumGreedy, Array, Math +2
2611Mice and CheeseMediumGreedy, Array, Sorting +1
2616Minimize the Maximum Difference of PairsMediumGreedy, Array, Binary Search +2
2645Minimum Additions to Make Valid StringMediumStack, Greedy, String +1
2673Make Costs of Paths Equal in a Binary TreeMediumGreedy, Tree, Array +2
2680Maximum ORMediumGreedy, Bit Manipulation, Array +1
2708Maximum Strength of a GroupMediumGreedy, Bit Manipulation, Array +4
2712Minimum Cost to Make All Characters EqualMediumGreedy, String, Dynamic Programming
2734Lexicographically Smallest String After Substring OperationMediumGreedy, String
2745Construct the Longest New StringMediumGreedy, Brainteaser, Math +1
2789Largest Element in an Array after Merge OperationsMediumGreedy, Array
2800Shortest String That Contains Three StringsMediumGreedy, String, Enumeration
2811Check if it is Possible to Split ArrayMediumGreedy, Array, Dynamic Programming
2829Determine the Minimum Sum of a k-avoiding ArrayMediumGreedy, Math
2834Find the Minimum Possible Sum of a Beautiful ArrayMediumGreedy, Math
2844Minimum Operations to Make a Special NumberMediumGreedy, Math, String +1
2847Smallest Number With Given Digit ProductPremiumMediumGreedy, Math
2856Minimum Array Length After Pair RemovalsMediumGreedy, Array, Hash Table +3
2870Minimum Number of Operations to Make Array EmptyMediumGreedy, Array, Hash Table +1
2871Split Array Into Maximum Number of SubarraysMediumGreedy, Bit Manipulation, Array
2892Minimizing Array After Replacing Pairs With Their ProductPremiumMediumGreedy, Array, Dynamic Programming
2895Minimum Processing TimeMediumGreedy, Array, Sorting
2910Minimum Number of Groups to Create a Valid AssignmentMediumGreedy, Array, Hash Table
2918Minimum Equal Sum of Two Arrays After Replacing ZerosMediumGreedy, Array
2938Separate Black and White BallsMediumGreedy, Two Pointers, String
2939Maximum Xor ProductMediumGreedy, Bit Manipulation, Math
2952Minimum Number of Coins to be AddedMediumGreedy, Array, Sorting
2957Remove Adjacent Almost-Equal CharactersMediumGreedy, String, Dynamic Programming
2966Divide Array Into Arrays With Max DifferenceMediumGreedy, Array, Sorting
2967Minimum Cost to Make Array EqualindromicMediumGreedy, Array, Math +2
2971Find Polygon With the Largest PerimeterMediumGreedy, Array, Prefix Sum +1

Hard (71)

#ProblemDifficultyTopics
44Wildcard MatchingHardGreedy, Recursion, String +1
135CandyHardGreedy, Array
321Create Maximum NumberHardStack, Greedy, Array +2
330Patching ArrayHardGreedy, Array
410Split Array Largest SumHardGreedy, Array, Binary Search +2
420Strong Password CheckerHardGreedy, String, Heap (Priority Queue)
502IPOHardGreedy, Array, Sorting +1
517Super Washing MachinesHardGreedy, Array
630Course Schedule IIIHardGreedy, Array, Sorting +1
632Smallest Range Covering Elements from K ListsHardGreedy, Array, Hash Table +3
358Rearrange String k Distance ApartPremiumHardGreedy, Hash Table, String +3
527Word AbbreviationPremiumHardGreedy, Trie, Array +2
757Set Intersection Size At Least TwoHardGreedy, Array, Sorting
765Couples Holding HandsHardGreedy, Depth-First Search, Breadth-First Search +2
768Max Chunks To Make Sorted IIHardStack, Greedy, Array +2
857Minimum Cost to Hire K WorkersHardGreedy, Array, Sorting +1
871Minimum Number of Refueling StopsHardGreedy, Array, Dynamic Programming +1
936Stamping The SequenceHardStack, Greedy, Queue +1
1147Longest Chunked Palindrome DecompositionHardGreedy, Two Pointers, String +3
1183Maximum Number of OnesPremiumHardGreedy, Math, Sorting +1
1199Minimum Time to Build BlocksPremiumHardGreedy, Array, Math +1
1326Minimum Number of Taps to Open to Water a GardenHardGreedy, Array, Dynamic Programming
1330Reverse Subarray To Maximize Array ValueHardGreedy, Array, Math
1363Largest Multiple of ThreeHardGreedy, Array, Math +2
1383Maximum Performance of a TeamHardGreedy, Array, Sorting +1
1388Pizza With 3n SlicesHardGreedy, Array, Dynamic Programming +1
1402Reducing DishesHardGreedy, Array, Dynamic Programming +1
1505Minimum Possible Integer After at Most K Adjacent Swaps On DigitsHardGreedy, Binary Indexed Tree, Segment Tree +1
1520Maximum Number of Non-Overlapping SubstringsHardGreedy, String
1526Minimum Number of Increments on Subarrays to Form a Target ArrayHardStack, Greedy, Array +2
1537Get the Maximum ScoreHardGreedy, Array, Two Pointers +1
1585Check If String Is Transformable With Substring Sort OperationsHardGreedy, String, Sorting
1665Minimum Initial Energy to Finish TasksHardGreedy, Array, Sorting
1671Minimum Number of Removals to Make Mountain ArrayHardGreedy, Array, Binary Search +1
1675Minimize Deviation in ArrayHardGreedy, Array, Ordered Set +1
1703Minimum Adjacent Swaps for K Consecutive OnesHardGreedy, Array, Prefix Sum +1
1713Minimum Operations to Make a SubsequenceHardGreedy, Array, Hash Table +1
1739Building BoxesHardGreedy, Math, Binary Search
1788Maximize the Beauty of the GardenPremiumHardGreedy, Array, Hash Table +1
2014Longest Subsequence Repeated k TimesHardGreedy, String, Backtracking +2
2030Smallest K-Length Subsequence With Occurrences of a LetterHardStack, Greedy, String +1
2071Maximum Number of Tasks You Can AssignHardGreedy, Queue, Array +4
2132Stamping the GridHardGreedy, Array, Matrix +1
2136Earliest Possible Day of Full BloomHardGreedy, Array, Sorting
2141Maximum Running Time of N ComputersHardGreedy, Array, Binary Search +1
2193Minimum Number of Moves to Make PalindromeHardGreedy, Binary Indexed Tree, Two Pointers +1
2234Maximum Total Beauty of the GardensHardGreedy, Array, Two Pointers +4
2263Make Array Non-decreasing or Non-increasingPremiumHardGreedy, Dynamic Programming
2350Shortest Impossible Sequence of RollsHardGreedy, Array, Hash Table
2366Minimum Replacements to Sort the ArrayHardGreedy, Array, Math
2412Minimum Money Required Before TransactionsHardGreedy, Array, Sorting
2448Minimum Cost to Make Array EqualHardGreedy, Array, Binary Search +2
2449Minimum Number of Operations to Make Arrays SimilarHardGreedy, Array, Sorting
2459Sort Array by Moving Items to Empty SpacePremiumHardGreedy, Array, Sorting
2472Maximum Number of Non-overlapping Palindrome SubstringsHardGreedy, Two Pointers, String +1
2499Minimum Total Cost to Make Arrays UnequalHardGreedy, Array, Hash Table +1
2528Maximize the Minimum Powered CityHardGreedy, Queue, Array +3
2551Put Marbles in BagsHardGreedy, Array, Sorting +1
2561Rearranging FruitsHardGreedy, Sort, Array +1
2573Find the String with LCPHardGreedy, Union Find, Array +3
2589Minimum Time to Complete All TasksHardStack, Greedy, Array +2
2659Make Array EmptyHardGreedy, Binary Indexed Tree, Segment Tree +4
2663Lexicographically Smallest Beautiful StringHardGreedy, String
2790Maximum Number of Groups With Increasing LengthHardGreedy, Array, Math +2
2813Maximum Elegance of a K-Length SubsequenceHardStack, Greedy, Array +3
2818Apply Operations to Maximize ScoreHardStack, Greedy, Array +4
2835Minimum Operations to Form Subsequence With Target SumHardGreedy, Bit Manipulation, Array
2842Count K-Subsequences of a String With Maximum BeautyHardGreedy, Hash Table, Math +2
2868The Wording GamePremiumHardGreedy, Array, Math +3
2897Apply Operations on Array to Maximize Sum of SquaresHardGreedy, Bit Manipulation, Array +1
2931Maximum Spending After Buying ItemsHardGreedy, Array, Matrix +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.

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.

Meet the greedy 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.