Greedy (LeetCode #15)
A greedy algorithm commits to the choice that looks best right now and never reconsiders. When that is provably safe, the code is short and fast; when it is not, it is subtly wrong. This post covers the eight NeetCode Greedy problems, each with the reasoning before the code.
The technique
Greedy is correct when a problem has the greedy choice property (some optimal solution starts with the local choice) and optimal substructure. The proof is an exchange argument: transform any optimal solution to use the greedy choice without making it worse. Code shape: one pass with one or two running values.
Counterexample warning: greedy fails for coin change and 0/1 knapsack. When you cannot prove the rule, test against brute force on small inputs.
Maximum Subarray
The question. Return the largest sum of any contiguous subarray.
Input: [-2,1,-3,4,-1,2,1,-5,4]
Output: 6 ([4,-1,2,1])
The idea — Kadane’s algorithm. At each position, decide whether to extend the current subarray or start fresh here. Extending is better only if the running sum is positive; a negative running sum would drag the new sum down.
\[ \text{cur} = \max(nums[i],\ \text{cur} + nums[i]) \]
Walk it through on the input: cur becomes -2, 1, -2, 4, 3, 5, 6, 1, 5; the best is 6.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.55cm, minimum height=0.5cm, font=\scriptsize\ttfamily}]
\foreach \v [count=\i from 0] in {-2,1,-3,4,-1,2,1,-5,4} { \node[c, fill=blue!6] at (\i*0.61,0.9) {\v}; }
\node[c, fill=orange!20] at (1.83,0) {4};
\draw[->, thick, orange!80!black] (1.22,0.6) -- (1.83,0.28);
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.83,-0.35) {restart here};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.4,-0.8) {negative running sum? start fresh};
\end{tikzpicture}
def max_subarray(nums):
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x) # extend or restart
best = max(best, cur)
return best
\(O(n)\) time, \(O(1)\) space.
Jump Game
The question. nums[i] is the max jump from i; can you reach the last index?
The idea. Track the farthest reachable index. If the current index is beyond it, you are stuck.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
\foreach \v [count=\i from 0] in {2,3,1,1,4} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\draw[->, thick, green!55!black] (0,0.28) to[bend left=30] (1.32,0.28);
\draw[->, thick, green!55!black] (0.66,0.28) to[bend left=30] (2.64,0.28);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.32,-0.55) {reach only grows; a gap means stuck};
\end{tikzpicture}
def can_jump(nums):
reach = 0
for i, x in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + x)
return True
\(O(n)\) time, \(O(1)\) space.
Jump Game II
The question. Minimum jumps to reach the last index.
The idea — BFS by levels. current_end is the boundary of the current jump’s reach; when you reach it, take another jump and extend to farthest.
def jump(nums):
jumps = current_end = farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == current_end:
jumps += 1
current_end = farthest
return jumps
\(O(n)\) time, \(O(1)\) space.
Gas Station
The question. Find the start station that completes the circular route, or -1.
The idea. If total gas ≥ total cost, a solution exists. Scan, tracking the running tank; when it goes negative, no start at or before this point works, so jump the start to the next station.
Walk it through on gas = [1,2,3,4,5], cost = [3,4,5,1,2] (net [-2,-2,-2,3,3], total 0):
i |
net | tank | tank < 0? |
start |
|---|---|---|---|---|
| 0 | −2 | −2 | yes | 1 |
| 1 | −2 | −2 | yes | 2 |
| 2 | −2 | −2 | yes | 3 |
| 3 | +3 | 3 | no | 3 |
| 4 | +3 | 6 | no | 3 |
Answer 3: from station 3 the tank never drops (3, then 6).
def can_complete(gas, cost):
if sum(gas) < sum(cost):
return -1
start = tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
tank = 0
return start
Why the jump is safe. If the tank goes negative at i for a start s ≤ i, every station between s and i has even less surplus left when reached, so none of them can complete the loop either. Skipping to i+1 discards only impossible starts.
Why total gas decides. The first check says a solution exists exactly when the whole loop nets non-negative: the unique surviving candidate then must work, because any failure point would move the start forward and the scan visits every station once.
Complexity. \(O(n)\) time, \(O(1)\) space.
Edge cases. Equal totals with all zeros → start 0. A single station with enough gas → 0.
Hand of Straights
The question. Can the cards be rearranged into groups of groupSize consecutive cards?
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 -> True
The idea. Always start a group at the smallest remaining card (it must be the start of some group). Take it and the next groupSize - 1 consecutive cards; if any is missing, return False. A sorted structure of counts lets us do this efficiently.
Walk it through. Smallest is 1 → take 1,2,3. Next smallest 2 → take 2,3,4. Next 6 → 6,7,8. All consumed → True.
from sortedcontainers import SortedDict
def is_n_straight_hand(hand, groupSize):
if len(hand) % groupSize:
return False
count = SortedDict()
for c in hand:
count[c] = count.get(c, 0) + 1
while count:
first = next(iter(count)) # smallest remaining card
for c in range(first, first + groupSize):
if c not in count:
return False # a gap -> impossible
count[c] -= 1
if count[c] == 0:
del count[c]
return True
\(O(n \log n)\) time with a sorted map.
Merge Triplets to Form Target Triplet
The question. From a list of triplets, can you merge some (taking the element-wise max) to form target?
Input: triplets = [[2,5,3],[1,8,4],[1,8,4]], target = [2,5,5] -> False
The idea. Merging takes element-wise maxima, so a triplet is only useful if no element exceeds the target’s corresponding element (otherwise the max would overshoot). Among the useful triplets, check whether each target coordinate is reached by at least one of them.
Walk it through. On the example, [2,5,3] is useful (all ≤ target) and reaches target[0]=2, target[1]=5; [1,8,4] is not useful (8 > 5), so target[2]=5 is never reached → False.
def merge_triplets(triplets, target):
reached = [False, False, False]
for t in triplets:
if all(t[i] <= target[i] for i in range(3)): # useful
for i in range(3):
if t[i] == target[i]:
reached[i] = True
return all(reached)
\(O(n)\) time, \(O(1)\) space.
Partition Labels
The question. Partition a string into as many parts as possible so each letter appears in at most one part.
The idea. Record each letter’s last index. Extend the current part to the maximum last-index seen; when the scan reaches it, close the part.
def partition_labels(s):
last = {ch: i for i, ch in enumerate(s)}
out, start, end = [], 0, 0
for i, ch in enumerate(s):
end = max(end, last[ch])
if i == end:
out.append(end - start + 1)
start = i + 1
return out
\(O(n)\) time.
Valid Parenthesis String
The question. A string has (, ), and *; * can be (, ), or empty. Is it valid?
Input: "(*)" -> True
Input: "(*))" -> True
The idea. Track the range of possible open counts [lo, hi]. ( increases both; ) decreases both; * can do either, so lo -= 1 and hi += 1. Clamp lo at 0 (never a negative count). The string is valid iff hi never drops below 0 (impossible to close) and lo reaches 0 at the end (a real way to close).
Walk it through on "(*))": lo,hi = (0,0) → ( (1,1) → * (0,2) → ) (0,1) → ) (0,0). hi ≥ 0 throughout and lo == 0 → True.
def check_valid_string(s):
lo = hi = 0
for ch in s:
if ch == "(":
lo += 1; hi += 1
elif ch == ")":
lo -= 1; hi -= 1
else: # "*"
lo -= 1; hi += 1
if hi < 0: # too many ')' even treating all '*' as '('
return False
lo = max(lo, 0) # open count cannot be negative
return lo == 0
\(O(n)\) time, \(O(1)\) space.
Pitfalls
- Assuming greedy works. Prove it or brute-check.
- Sorting by the wrong key. Interval scheduling needs end time.
- Kadane’s restart rule. Only restart when the running sum is negative.
- Hand of Straights starting mid-group. Always start at the smallest remaining card.
- Merge Triplets skipping the “useful” filter. A triplet exceeding the target can never be merged.
What running value makes Maximum Subarray greedy correct? Why does Hand of Straights always start with the smallest card?
ASolution
The best subarray ending at the current index: extend if the running sum is positive, otherwise restart. The smallest remaining card cannot be the continuation of a group, so it must start a new consecutive group; taking its group immediately is forced, which is why the greedy is safe.
Next: Intervals (LeetCode #16) — sort, sweep, and merge.