- Related Questions & Answers
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check robot can reach target position or not in Python
- Program to check we can reach end of list by starting from k in Python
- Program to find number of minimum steps to reach last index in Python
- Program to check we can update a list index by its current sum to reach target or not in python
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check whether we can form 24 by placing operators in python
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check whether we can get N queens solution or not in Python
- Program to check whether we can stand at least k distance away from the closest contacts in Python
- Program to check we can make arithmetic progression from sequence in Python
- Program to check whether we can convert string in K moves or not using Python
- Program to check we can form array from pieces or not in Python
- Program to check whether we can split list into consecutive increasing sublists or not in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

[2,5,0,2,0]

True

Advertisements