We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Jump Game

Difficulty: Medium


Problem Description

You are given an integer array nums. You are initially positioned at the array's 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.


Key Insights

  • Each element in the array represents the maximum jump length from that position.
  • If at any position you can reach beyond the last index, you can successfully complete the jump.
  • The problem can be solved using a greedy approach, where we track the farthest point we can reach as we iterate through the array.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

The solution uses a greedy approach to keep track of the farthest index that can be reached as we iterate through the array. We initialize a variable farthest to zero, which represents the farthest index that we can currently reach. As we loop through each index, we check if the current index is reachable (i.e., if it is less than or equal to farthest). If it is, we update farthest to be the maximum of its current value or the sum of the current index and the jump length at that index. If farthest reaches or exceeds the last index during this process, we return true. If we finish the loop without being able to reach the last index, we return false.


Code Solutions

def canJump(nums):
    farthest = 0
    for i in range(len(nums)):
        if i > farthest:
            return False
        farthest = max(farthest, i + nums[i])
        if farthest >= len(nums) - 1:
            return True
    return False
← Back to All Questions