- Related Questions & Answers
- Program to check whether we can reach last position from index 0 in Python
- Program to check we can update a list index by its current sum to reach target or not in python
- Check if the given number K is enough to reach the end of an array in Python
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check robot can reach target by keep moving on visited spots in Python
- Program to check we can spell out the target by a list of words or not in Python
- Program to check whether we can partition a list with k-partitions of equal sum in C++
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to reverse linked list by groups of size k in Python
- Program to check robot can reach target position or not in Python
- Program to check whether we can stand at least k distance away from the closest contacts in Python
- List expansion by K in Python
- Program to find number of ways we can reach from top left point to bottom right point in Python
- Program to find minimum number of hops required to reach end position in Python
- Program to check whether we can form 24 by placing operators 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 and another number k. If we start at index k and at any index i, we can go either left or right by exactly nums[i] number of steps. We have to check whether we can reach the end of the list or not.

So, if the input is like nums = [0, 0, 2, 1, 3, 3, 1, 1] k = 2, then the output will be True, as if we start at index 2, then jump to index 4 and then jump to the last index 7.

To solve this, we will follow these steps−

n:= size of nums

visited := a list of size n and fill with 0

tovisit := a list of size 1, and insert k into it

while size of tovisit < 0, do

i:= last element from tovisit and delete it from tovisit

if i is same as n-1, then

return True

if visited[i] is not same as 1, then

visited[i]:= 1

up:= i + nums[i]

down:= i - nums[i]

if up < n, then

insert up at the end of tovisit

if down >= 0, then

insert down at the end of tovisit

return False

Let us see the following implementation to get better understanding−

class Solution: def solve(self, nums, k): n=len(nums) visited = [0]*n tovisit = [k] while len(tovisit)>0: i=tovisit.pop() if i==n-1: return True if visited[i]!=1: visited[i]=1 up=i+nums[i] dn=i-nums[i] if up=0: tovisit.append(dn) return False ob = Solution() nums = [0, 0, 2, 1, 3, 3, 1, 1] k = 2 print(ob.solve(nums, k))

[0, 0, 2, 1, 3, 3, 1, 1], 2

True

Advertisements