Greedy
common questions
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β
| Pattern | Use when | Example |
|---|---|---|
| Track the furthest reach | Reachability, minimum jumps | Jump Game, Jump Game II |
| Sort by end, then sweep | Interval scheduling: keep the most non-overlapping intervals | Non-overlapping Intervals, Min Arrows |
| Sort by start, then merge | Merging or inserting intervals | Merge Intervals, Insert Interval |
| Running balance, reset when negative | A deficit can't be recovered from this start point | Gas Station, Kadane's |
| Last occurrence | Cut as early as allowed | Partition Labels |
| Heap of best-so-far | Pick the best option seen so far, only when forced | Task Scheduler, IPO |
| Two pointers from both ends | Pair the largest with the smallest | Boats 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 by | Example | Result |
|---|---|---|
| End | [[1, 10], [2, 3], [4, 5]]: keeps [2, 3], [4, 5] | β Removes 1 |
| Start | Same 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β
| Problem | Greedy choice | Counterexample | Use instead |
|---|---|---|---|
Coin change, coins [1, 3, 4] | Largest coin first | Amount 6: greedy 4 + 1 + 1 (3 coins), optimal 3 + 3 (2) | DP |
| 0/1 knapsack | Best value per weight | Capacity 10, items (w 6, v 7), (w 5, v 5), (w 5, v 5): greedy 7, optimal 10 | DP |
| Jump Game | Furthest reach | None: 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
goalfrom end of array. - Move
goalvariable 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.