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

###### https://www.tutorialspoint.com/program-to-check-whether-we-can-reach-last-position-from-index-0-in-python

### Full question

- python - programming - Server Side Programming |
- |

### Question

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

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

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

Advertisements

Not affiliated with Tutorialspoint