Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Greedy

Greedy

O(n log n)

Sort or scan and commit to the best immediate move; the hard part is proving the greedy choice is safe.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksBinary Search on the AnswerMinimum Spanning Tree
0%
mastery
0/91 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

"Minimum number of ...", scheduling, reachability or coverage where sorting by one key and a single pass gives the answer.

  1. 1Brute force

    Try all choices (exponential) or DP.

  2. 2The observation

    Exploring alternatives: a proof shows some optimal solution agrees with the greedy choice.

  3. 3Why it works

    After k steps the greedy partial solution can still be extended to an optimal one (prove it with an exchange argument).

Reach for it when

  • +A locally optimal choice is provably globally optimal — interval scheduling, jumps, 'minimum number of …'.
  • +Sorting by a clever key makes the answer fall out in one pass.
  • +Problems about reachability, coverage, or scheduling with a clean exchange argument.

Not when

  • ×Choices interact later (knapsack, weighted scheduling)use Dynamic programming
  • ×A small counterexample breaks the rule (coin change, non-canonical coins)use DP
  • ×You need to count ways or explore alternativesuse DP or backtracking
  • ×You think passing the samples means it's correctuse Try to break it on small adversarial cases first

Intuition

Greedy means: at each step take the choice that looks best right now, never reconsider, and trust it adds up to the global best. When it works it's gorgeous — one pass, O(n) or O(n log n) after a sort. The catch is the proof: greedy is only correct if a locally-best move can't paint you into a corner later.

Read the full intuition

The classic worked example — Jump Game ("can you reach the end?"): track the farthest index reachable so far. Sweep left to right; at each reachable i, update reach = max(reach, i + nums[i]). If i > reach you're stuck → false. You never plan a route; you just keep the best frontier. One pass.

Maximum Subarray (Kadane's) is greedy too: keep a running sum; if it goes negative it can only hurt what's next, so drop it (reset to 0) and track the best seen. Gas Station: if total gas ≥ total cost a solution exists, and the start is just after the point where your running tank dips lowest.

Key idea

How to tell greedy from DP: if a locally optimal choice is provably safe (the right sort key, a clear exchange argument), greedy. If choices interact and you might need to undo one, it's DP. A plausible greedy is often subtly wrong — verify on small cases.

Why it costs what it costs

Time O(n) or O(n log n). a single linear scan, plus a sort or a heap when ordering is needed.

Space O(1)–O(n). a few scalars; O(n) if a heap or frequency map is involved.

Practice

Next · Foundation

Best Time to Buy and Sell Stock II

Unlimited transactions decompose into daily gains.

0/91 solved
  • Best Time to Buy and Sell Stock IIFoundationFoundationAmazon, CitadelMedium
  • Jump GameApply it · Track furthest reach.Apply itAmazon, MetaMedium
  • Jump Game IIOne change · Minimum jumps.One changeAmazon, MetaMedium
  • Partition LabelsOne change · Use last occurrence.One changeAmazon, MetaMedium
  • Gas StationTwists · Circular route.TwistsAmazon, UberMedium
  • Movie FestivalBranches · Interval scheduling.BranchesCSESMedium
  • Hand of StraightsBranches · Smallest card must start a group.BranchesGoogle, UberMedium
  • Task SchedulerCombine · Counting argument vs simulation.CombineMeta, AmazonMedium
  • CandyAdvanced · Two-sided constraint.AdvancedAmazon, CitadelHard
  • Valid Parenthesis StringMastery checkMastery checkMeta, AmazonMedium
  • Maximum SubarrayAmazon, MicrosoftMedium
  • Boats to Save PeopleUber, AmazonMedium

Pitfalls

Classic bugs

  • !Wrong sort key chosen by intuition: derive it from swapping two adjacent items (interval scheduling sorts by end).
  • !Kadane: record the best before resetting a negative running sum, or all-negative arrays break.
  • !Gas Station needs both the total-feasibility check and restarting the start index after the lowest point.
  • !Jump frontier: off-by-one in i + nums[i], and a missing early exit when i passes the reachable frontier.

Looks like it, isn't

  • Russian Doll Envelopes needs Longest Increasing Subsequence
    Why
    Greedy by width fails; sort (w asc, h desc) and run LIS on heights.
  • Binary Tree Cameras needs DP on Trees
    Why
    Top-down greedy (cameras on the leaves) fails. A three-state tree DP works, and so does the bottom-up greedy (a camera at the parent of the deepest uncovered node), which the DP proves. source ↗
  • Delete and Earn needs 1D / Fibonacci-style
    Why
    Taking x deletes x-1 and x+1: after bucketing values it is house robber.
  • Coin Change needs Unbounded Knapsack
    Why
    Largest-coin-first fails for arbitrary denominations.
  • Remove K Digits needs Monotonic Stack
    Why
    The greedy 'drop a digit larger than the next' is implemented by a monotonic stack.
  • Minimum Cost to Move Chips to The Same Position needs Invariants & Parity Arguments
    Why
    Moves by 2 are free, so only parity matters: the answer is min(#odd, #even). source ↗
  • Largest Number needs Exchange-Argument Sorting (custom comparator)
    Why
    Sorting by value fails ('3' vs '30'). The editorial uses a custom comparator a+b vs b+a. source ↗
  • Minimum XOR Sum of Two Arrays needs Bitmask DP
    Why
    Assignment with n <= 14. Greedy pairing fails. dp[mask] over the matched elements of nums2 (Hungarian / min-cost-flow also works). source ↗
  • Minimum Total Distance Traveled needs LCS / Two-Sequence
    Why
    Nearest-factory greedy fails on capacities. After sorting, an optimal matching is non-crossing, which gives a two-sequence DP (editorial memoisation). source ↗
Go deepervariants and techniques · 12 combinations · resources

Variants and techniques

  • Interval Scheduling (sort by end)To pick the most non-overlapping intervals (or fewest points stabbing all), sort by END and greedily take the earliest-finishing compatible one.
  • Greedy with a Heap (regret / exchange later)Take items greedily, keep taken items in a heap, and when a constraint breaks, undo the worst earlier choice (or swap it for a better one).
  • Constructive AlgorithmsCP 1600Prove when an object (array, permutation, grid, graph) exists, and build it directly. Usually: solve tiny cases by hand, spot the pattern, and handle a few parity or size cases.
  • Exchange-Argument Sorting (custom comparator)Interview · mediumWhen the cost of an order changes only through adjacent swaps, compare two items by which order is better when they sit next to each other (a+b vs b+a, a*b vs b*a, d_a - c_a). Sort by that comparator, then scan or run a DP.
  • Running best (Kadane)Drop a prefix that turns negative; track the max. Maximum Subarray.
  • Reachability frontierTrack farthest reachable / fewest jumps. Jump Game I/II.
  • Feasibility + restartTotal check then restart after the lowest dip. Gas Station.
  • Sort then sweepSort by the safe key, take non-conflicting greedily. Partition Labels (last-seen index).
  • Greedy + heapAlways serve the most frequent / most profitable next. Task Scheduler, IPO.

Combinations

  • Binary Search on the Answer+Greedy

    minimise the maximum / maximise the minimum over splits, speeds, or capacities

    Binary Search on the Answer:
    turns optimisation into a yes/no question
    Greedy:
    answers the fixed-threshold question in O(n): a greedy fill (split array, ship packages) or a monotone count (Factory Machines: sum of t/k_i >= n)

    Split Array Largest SumCapacity To Ship Packages Within D DaysKoko Eating Bananas

  • Greedy+Two Pointers

    pair people/items under a capacity with minimum groups

    Greedy:
    pairing rule justified by exchange
    Two Pointers:
    realises the pairing on a sorted array

    Boats to Save PeopleFerris WheelApartments

  • Greedy+Top-K Elements

    repeatedly pick the most frequent/cheapest/available item; time-based simulation

    Greedy:
    decides which item to take next
    Top-K Elements:
    retrieves the current best item in O(log n)

    Reorganize StringSingle-Threaded CPUTask Scheduler

  • Minimum Spanning Tree+Union-Find (Disjoint Set)+Greedy

    connect all nodes at minimum cost

    Minimum Spanning Tree:
    the goal (spanning tree)
    Union-Find (Disjoint Set):
    cycle check per edge
    Greedy:
    process edges by increasing weight (cut property)

    Connecting Cities With Minimum CostRoad ReparationMin Cost to Connect All Points

  • Greedy+Ordered Set / Balanced BST (TreeMap, multiset)

    match customers to the highest ticket <= budget; assign k members to movies

    Greedy:
    assigns each request the best remaining resource
    Ordered Set / Balanced BST (TreeMap, multiset):
    finds the floor/ceiling resource and removes it

    Concert TicketsMovie Festival IIRoom Allocation

  • Greedy with a Heap (regret / exchange later)+Top-K Elements

    survive constraints over time (health, bricks), maximise count taken

    Greedy with a Heap (regret / exchange later):
    take greedily, undo the worst past choice when a constraint breaks
    Top-K Elements:
    min-heap of taken items

    Furthest Building You Can ReachPotions (Hard Version)Buy Low Sell High

  • Interval Scheduling (sort by end)+1D / Fibonacci-style+Binary Search

    choose non-overlapping intervals maximising total weight (or at most k of them)

    Interval Scheduling (sort by end):
    sort by end so that compatible predecessors form a prefix
    1D / Fibonacci-style:
    dp[i] = max(dp[i-1], w_i + dp[p(i)])
    Binary Search:
    find the last job ending at or before the current start

    Maximum Profit in Job SchedulingMaximum Number of Events That Can Be Attended IIProjects

  • Exchange-Argument Sorting (custom comparator)+0/1 Knapsack

    choose and order projects/rewards with requirement and change values to maximise the count/total

    Exchange-Argument Sorting (custom comparator):
    fixes the processing order (gains first; losses by a_i + b_i descending)
    0/1 Knapsack:
    picks the subset to take, in that order

    Complete the Projects (hard version)Maximum Total Reward Using Operations I

  • Exchange-Argument Sorting (custom comparator)+Top-K Elements

    choose exactly a items for role A and b items for role B, maximising the total

    Exchange-Argument Sorting (custom comparator):
    sort by a_i - b_i so some prefix goes to group A and the rest to group B
    Top-K Elements:
    a heap keeps the best a values in the prefix and the best b values in the suffix

    Programmers and Artists

  • Greedy+Difference Array & Line Sweep

    minimum number of fixed-length range flips/increments to reach a target

    Greedy:
    the leftmost position that needs a flip/increment must be handled now
    Difference Array & Line Sweep:
    records where the effect of each applied operation ends, giving O(1) per position

    Minimum Number of K Consecutive Bit FlipsMinimum Number of Increments on Subarrays to Form a Target Array

  • Exchange-Argument Sorting (custom comparator)+LCS / Two-Sequence

    match points on a line to capacity-limited targets minimising the total distance

    Exchange-Argument Sorting (custom comparator):
    sort both robots and factories; an optimal matching never crosses
    LCS / Two-Sequence:
    two-sequence DP: dp[i][j] = robots i.. assigned to factories j..

    Minimum Total Distance Traveled

  • Binary Lifting & LCA+Interval Scheduling (sort by end)

    many queries: how many non-overlapping intervals fit inside [a, b]

    Binary Lifting & LCA:
    jump 2^k greedy steps at once
    Interval Scheduling (sort by end):
    from time t, the greedy next movie is the one ending earliest among those starting >= t

    Movie Festival Queries

Resources

  • Greedy Algorithms with SortingUSACO Guide · course
  • Greedy Algorithms (chapter)Jeff Erickson · book
  • Exchange arguments (sorting with dp)Errichto · blog
  • Algorithms playlistAbdul Bari · video
  • Competitive Programmer's HandbookAntti Laaksonen · book
Bit Tricks & BitmaskingSystem / DS Design
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial