Algorithm Day79 - Jump Game

🧩 Problem Description

You are given an integer array nums. You are initially positioned at the first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.


πŸ’¬ Examples

Example 1

1
2
3
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2

1
2
3
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 with a maximum jump length 0, so cannot move forward.

πŸ’‘ Intuition

We need to check whether it’s possible to reach the last index:

  • Keep track of the farthest position reachable while traversing the array.
  • If at any index i, i > farthest, then we cannot reach this index β†’ return false.
  • Otherwise, update farthest = max(farthest, i + nums[i]).
  • If the farthest index is at least the last index, return true.

This is a classic greedy approach.


πŸ”’ Java Code (Greedy)

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean canJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.length; i++) {
if (i > farthest) return false;
farthest = Math.max(farthest, i + nums[i]);
}
return true;
}
}

⏱ Complexity Analysis

  • Time: O(n) β€” single pass.
  • Space: O(1).

✍️ Summary

  • Maintain the farthest index reachable while iterating.
  • If you ever get stuck (i > farthest), return false.
  • Greedy solution ensures linear time complexity.

Related problems

  • lc-45 β€” Jump Game II
  • lc-1306 β€” Jump Game III
  • lc-1345 β€” Jump Game IV