Algo-Sim › Greedy

Jump Game

Medium · Greedy · step through it in Java, Python and C++ on your own input

Each value is the longest jump from that index. Can you reach the last index? Track the farthest reachable index in one pass.

Problem

You start at index 0 of nums, and nums[i] is the longest jump you may take from index i (any shorter jump is fine too). Return true if you can reach the last index, false otherwise.

Constraints

Edge cases to test

Follow-up questions

What is the minimum number of jumps?
Treat the reachable range as BFS levels and count level changes (LC 45): O(n).
Is there a backward greedy?
Walk from the end, moving the goal to any index that can reach it; the answer is whether the goal reaches 0.

Solution

Java

public boolean canJump(int[] nums) {
    int reach = 0;
    for (int i = 0; i < nums.length; i++) {
        if (i > reach) return false;
        reach = Math.max(reach, i + nums[i]);
        if (reach >= nums.length - 1) return true;
    }
    return true;
}

Python

def can_jump(nums):
    reach = 0
    for i, x in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + x)
        if reach >= len(nums) - 1:
            return True
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool canJump(vector<int> &nums) {
        int reach = 0;
        for (int i = 0; i < int(nums.size()); i++) {
            if (i > reach)
                return false;
            reach = std::max(reach, i + nums[i]);
            if (reach >= int(nums.size()) - 1)
                return true;
        }
        return true;
    }
};

More Greedy problems