Arrays & Hashing · Pattern 17 of 26
Greedy: make the safe choice now
Make the choice that looks best right now and never undo it. It works when you can argue that some best answer always starts with that choice; usually after sorting.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- "Minimum number of jumps / taps / coins to cover"
- Pick items by value per unit, or pair the largest with the smallest
- A local rule (place a flower if both neighbours are empty) is clearly safe
The template
// can you reach the last index? keep the farthest reachable index
boolean canJump(int[] nums) {
int far = 0;
for (int i = 0; i < nums.length; i++) {
if (i > far) return false; // stuck before i
far = Math.max(far, i + nums[i]);
}
return true;
}
// minimum jumps: BFS by levels, each level is the range one more jump can reach
int jump(int[] nums) {
int jumps = 0, end = 0, far = 0;
for (int i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]);
if (i == end) { jumps++; end = far; } // must jump again to go further
}
return jumps;
} def can_jump(nums): # keep the farthest reachable index
far = 0
for i, x in enumerate(nums):
if i > far:
return False # stuck before i
far = max(far, i + x)
return True
def jump(nums): # minimum jumps, one "level" per jump
jumps = end = far = 0
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
if i == end: # must jump again to go further
jumps += 1
end = far
return jumps // can you reach the last index? keep the farthest reachable index
bool canJump(vector<int>& nums) {
int far = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (i > far) return false; // stuck before i
far = max(far, i + nums[i]);
}
return true;
}
// minimum jumps: each level is the range one more jump can reach
int jump(vector<int>& nums) {
int jumps = 0, end = 0, far = 0;
for (int i = 0; i + 1 < (int)nums.size(); i++) {
far = max(far, i + nums[i]);
if (i == end) { jumps++; end = far; } // must jump again to go further
}
return jumps;
} // can you reach the last index? keep the farthest reachable index
function canJump(nums) {
let far = 0;
for (let i = 0; i < nums.length; i++) {
if (i > far) return false; // stuck before i
far = Math.max(far, i + nums[i]);
}
return true;
}
// minimum jumps: each level is the range one more jump can reach
function jump(nums) {
let jumps = 0, end = 0, far = 0;
for (let i = 0; i < nums.length - 1; i++) {
far = Math.max(far, i + nums[i]);
if (i === end) { jumps++; end = far; } // must jump again to go further
}
return jumps;
} The variations
-
1Reach as far as you can
Track the farthest point reachable so far. Jumps, taps and "coins needed to cover 1..target" all extend a covered range greedily.
Now you solve -
2Sort, then decide in order
After sorting by the right key, the best choice at each step is obvious: most units per box, biggest cost difference, tallest first, match the strongest opponent you can beat.
Now you solve- Two City Scheduling Medium Stuck? solution
- Queue Reconstruction by Height Medium Stuck? solution
- Advantage Shuffle Medium Stuck? solution
- Minimum Absolute Difference Easy Stuck? solution
- Largest Number Medium Stuck? solution
- Maximum Product of Three Numbers Easy Stuck? solution
- Make Lexicographically Smallest Array by Swapping Elements Medium Stuck? solution
- Minimize Rounding Error to Meet Target Medium Stuck? solution
- Minimum Number of Operations to Make Arrays Similar Hard Stuck? solution
- Maximize Greatness of an Array Medium Stuck? ▶ video
-
3Most frequent first
The most frequent item decides the layout: place it with gaps, then fill the gaps. (max count − 1) × (n + 1) + ties is the task scheduler formula.
Now you solve- Reorganize String Medium Stuck? solution
-
4Two passes, left then right
Satisfy the rule with the left neighbour in a forward pass, then with the right neighbour in a backward pass, keeping the max of both.
-
5Local choices that never need undoing
Each step has a rule that is clearly safe: plant if both neighbours are empty, take the largest Roman symbol that fits, the answer is the largest digit.
Now you solve- Integer to Roman Medium Stuck? solution
- Minimum Domino Rotations For Equal Row Medium Stuck? solution
- Partitioning Into Minimum Number Of Deci-Binary Numbers Medium Stuck? solution
- Maximum Distance Between Unequal Words in Array I Easy Stuck? solution
- Minimum Operations to Make Array Equal II Medium Stuck? solution
- Transform Array to All Equal Elements Medium Stuck? solution
- Minimum Total Cost to Make Arrays Unequal Hard Stuck? solution
- Guess the Word Hard Stuck? solution
-
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Trusting a greedy rule without a reason. Try to break it with a small counterexample first; if it breaks, it is DP.
- Sorting by the wrong key (by cost instead of by the difference of costs, for example).
- Custom comparators that are not consistent (largest number: compare a + b with b + a).
Lesson done
Next: Hash set lookups →Mark it done once you can write the template from memory and you have solved the worked examples yourself.