# Program to check whether we can reach last position from index 0 in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a list of numbers called nums where each number shows the maximum number of jumps we can make; we have to check whether we can reach to the last index starting at index 0 or not.

So, if the input is like nums = [2,5,0,2,0], then the output will be True, as we can jump from index 0 to 1, then jump from index 1 to end.

To solve this, we will follow these steps−

• n := size of nums

• arr := an array of size n and fill with false

• arr[n - 1] := True

• for i in range n - 2 to 0, decrease by 1, do

• arr[i] := true if any one of arr[from index i + 1 to i + nums[i]] is true

• return arr[0]

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums):
n = len(nums)
arr = [False] * n
arr[n - 1] = True
for i in range(n - 2, -1, -1):
arr[i] = any(arr[i + 1 : i + nums[i] + 1])
return arr[0]
ob = Solution()
nums = [2,5,0,2,0]
print(ob.solve(nums))

## Input

[2,5,0,2,0]

## Output

True
Updated on 09-Oct-2020 13:40:03