55. Jump Game
Asked at 31Amazon66Bloomberg61Microsoft57Google56Meta50Apple35Infosys58Nike89Nielsen88HashedIn79Navi79Mastercard75Adobe69Shopee69Zoho65Turing55Morgan Stanley54PhonePe53Karat51ByteDance50TikTok50Agoda48Nvidia48Cognizant48tcs46Oracle45Flipkart43PayPal42Visa39Goldman Sachs36DoorDash36
Problem
You start at index 0, and nums[i] is the maximum jump length from index i. Decide whether you can reach the last index.
Example: [2,3,1,1,4] → true; [3,2,1,0,4] → false
Constraints: n ≤ 10⁴.
Track the farthest reachable index; if you ever stand beyond it, you're stuck.
Complexity: O(n) time, O(1) space.
class Solution:
def canJump(self, nums: List[int]) -> bool:
reach = 0
for i, x in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + x)
return True
assert Solution().canJump([2, 3, 1, 1, 4]) is True
assert Solution().canJump([3, 2, 1, 0, 4]) is False
class Solution {
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]);
}
return true;
}
}
func canJump(nums []int) bool {
reach := 0 // farthest index reachable so far
for i, x := range nums {
if i > reach {
return false
}
reach = max(reach, i+x)
}
return true
}