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
- 1 ≤ nums.length ≤ 10⁴
- 0 ≤ nums[i] ≤ 10⁵
- A 0 is a trap only if nothing can jump past it
Edge cases to test
- One element: already there
- A zero you can’t jump over:
[3, 2, 1, 0, 4] - A zero at the last index is fine
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 TrueC++
#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
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)