Skip to main content

Greedy

Greedy takes the locally best choice and never revisits it. It's O(n) or O(n log n) when it works, and silently wrong when it doesn't. Before using it, either find a counterexample or argue that swapping any optimal solution's choice for the greedy one is no worse (the exchange argument).

Common Approaches to Greedy Questions​

PatternUse whenExample
Track the furthest reachReachability, minimum jumpsJump Game, Jump Game II
Sort by end, then sweepInterval scheduling: keep the most non-overlapping intervalsNon-overlapping Intervals, Min Arrows
Sort by start, then mergeMerging or inserting intervalsMerge Intervals, Insert Interval
Running balance, reset when negativeA deficit can't be recovered from this start pointGas Station, Kadane's
Last occurrenceCut as early as allowedPartition Labels
Heap of best-so-farPick the best option seen so far, only when forcedTask Scheduler, IPO
Two pointers from both endsPair the largest with the smallestBoats to Save People

Interval scheduling​

Sort by end time and keep every interval that starts after the last kept one ends. Ending earliest leaves the most room for the rest.

def eraseOverlapIntervals(intervals):
intervals.sort(key=lambda x: x[1]) # by end
kept, end = 0, float("-inf")
for s, e in intervals:
if s >= end: # no overlap with the last kept interval
kept += 1
end = e
return len(intervals) - kept # removed
Sort byExampleResult
End[[1, 10], [2, 3], [4, 5]]: keeps [2, 3], [4, 5]βœ… Removes 1
StartSame input: keeps [1, 10], which blocks the others❌ Removes 2
Shortest first[[1, 4], [3, 5], [4, 7]]: keeps [3, 5], which blocks both❌ Removes 2, optimal removes 1

When greedy is wrong​

ProblemGreedy choiceCounterexampleUse instead
Coin change, coins [1, 3, 4]Largest coin firstAmount 6: greedy 4 + 1 + 1 (3 coins), optimal 3 + 3 (2)DP
0/1 knapsackBest value per weightCapacity 10, items (w 6, v 7), (w 5, v 5), (w 5, v 5): greedy 7, optimal 10DP
Jump GameFurthest reachNone: reach only grows, so greedy is exactβœ… Greedy

Example Solutions​

Jump Game​

Source

Video explanation by NeetCode.

Solution 1: Greedy Approach (Preferred Solution)​

  • Set variable goal from end of array.
  • Move goal variable from reverse order of the array until 0 is reached.
def canJump(self, nums):
goal = len(nums) - 1
for i in range(len(nums) - 2, -1, -1):
if nums[i] >= (goal - i): # if can jump to goal from i
goal = i # update goal to i
return goal == 0

Time Complexity: O(n) for one-pass of the nums array.

Space Complexity: O(1).


Solution 2: Dynamic Programming​

Source

Explanation by LeetCode discussions.

def canJump(self, nums):
dp = [False] * len(nums)
dp[-1] = True
for i in range(len(nums)-2, -1, -1):
for j in range(i + 1, min(len(nums), i + nums[i] + 1)): # Check all possible jumps from i
if dp[j]:
dp[i] = True
break
return dp[0]

Time Complexity: O(N^2) due to double for-loops for dynamic programming solution.

Space Complexity: O(N) for size of dp.