Jump Game I

Can you reach the last index? Track the maximum reachable index in one greedy pass.

Medium
Time O(n) Space O(1)
LeetCode
2 min read
greedy array

Problem#

nums[i] is your max jump length from index i. Return true iff you can reach the last index starting from index 0.

Examples#

  • [2,3,1,1,4]true
  • [3,2,1,0,4]false

Constraints#

  • 1 <= n <= 10^4.

Approach#

Walk left to right tracking farthest = max(farthest, i + nums[i]). If i > farthest, we’re stuck. Stop early if farthest >= n - 1.

Solution#

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

Editorial#

Greedy on reachability. We never need to “choose” a jump distance — if any earlier index can reach i, we can be there, and from there we can extend the reach as far as i + nums[i]. The only failure mode is i > farthest, which means a zero (or short jump) blocked us.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.