2Brute2Best
🔥0
03

Reachability / farthest reach (Greedy Sub-pattern)

Moves only go forward and any index up to the frontier is usable, so the whole state is one number: the farthest index you can reach.

Signals in the problem statement
  • ›

    "can you reach the last index"

  • ›

    "minimum number of jumps"

  • ›

    jump lengths are upper bounds (nums[i] = max jump)

What makes it different

Can you reach → one far variable. Minimum jumps → BFS levels [start, curEnd]. Jumps to exactly i ± nums[i] → not a prefix any more; use BFS / DFS with visited.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Jump Game
    Basic Anchor·LeetCode #55
    Medium
  2. 2
    Jump Game II
    Basic Reinforcement·LeetCode #45
    Medium
  3. 3
    Jump Game III
    Pattern Transfer·LeetCode #1306
    Medium

Template

reach-template.cpp
// nums[i] = longest jump from i. Every index up to far is reachable.
bool canReachEnd(const vector<int>& nums) {
    int far = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        if (i > far) return false;                           // a gap nobody can jump over
        far = max(far, i + nums[i]);
    }
    return true;
}

// Fewest jumps: indexes reachable with k jumps form one block [.., curEnd] (a BFS level).
int minJumps(const vector<int>& nums) {
    int jumps = 0, curEnd = 0, far = 0;
    for (int i = 0; i + 1 < (int)nums.size(); i++) {
        far = max(far, i + nums[i]);
        if (i == curEnd) { jumps++; curEnd = far; }          // level finished: one more jump
    }
    return jumps;                                            // assumes the end is reachable
}
Remember this · Greedy
Trigger
Maximise count / minimise cost with a natural "best next step", sorting makes the choice obvious, reachability.
Think
Is there a choice I can always make safely without looking ahead?
Key question
Why can't the greedy choice be worse than the optimal one? (Try to break it with a small example.)