 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
 