0055-jump-game

Try it on leetcode

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.

 

Example 1:

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:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

 

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 105

Solution(Python)

class Solution:
    def canJump(self, nums: List[int]) -> bool:
    #  [2,3,1,1,4]
    #  i =0 :2 
    #    0 1 2 
    #   i = 1: 3
    #     3 4  5
    #  
    # At index 0  and value 2 it can react indices 0 1 2

    # at index 1 value 3 :  3 4 5 6

    # at index i farthest point the value at the index 
    #  
    # Example 2
    # 
    #  nums = [3,2,1,0,4]
    # 
    #  i = 0 : value = 3 
    #    1 2 3
    #  i =3 -> i= 0 recursion
    #  i = 2  -> i =3
    #  i = 1 -> i=3
    #
    # At index i with value nums[i]  -> 1, 2, 3...nums[i]
    # What's the one key piece of information you need to maintain as you scan through?
    # In other words: at any point, what do you need to know about all the indices you've seen so far?

    # Think about it differently: What would make an index unreachable?
    #  As you move left to right, you only need to track: "What is the farthest index I can reach so far?"
    #  
    # is index i even reachable?
    # if not reachable can we keep going
    #  nums = [3,2,10,4]
    # i = 0: value =3 farthest reach = 0 + 3
    #    isreach(0) = True
    # i =1 : value = 2 potential reach = 2+ 1 = 3
    #   isreach(1) = true
    #   furthest reach = max(3, 3)
    # i =2: value =1  potentialreach = 2 + 1 = 3
    #   isreach(2) = True
    #  farthestreach = 3
    #i =4: value=4
    # isreach(4) 
        farthest_reach = 0
        n = len(nums)
        if n == 1:
            return True
        for i, num in enumerate(nums):
            if i > farthest_reach:
                break
            farthest_reach = max(farthest_reach, i + num)
            if farthest_reach >= n - 1:
                return True
        return farthest_reach >= len(nums) - 1
    #
    # Why is the greedy approach safe here? You're always picking the maximum reach at each step—but what if a smaller jump is actually the "right" choice? Why doesn't that matter?