Jump Game 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 an array of non-negative integers; we are initially positioned at the first index of the array. Each element in the given array represents out maximum jump length at that position. We have to determine if we are able to reach the last index or not. So if the array is like [2,3,1,1,4], then the output will be true. This is like jump one step from position 0 to 1, then three step from position 1 to the end.

Let us see the steps −

• n := length of array A – 1
• for i := n – 1, down to -1
• if A[i] + i > n, then n := i
• return true when n = 0, otherwise false

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution(object):
def canJump(self, nums):
n = len(nums)-1
for i in range(n-1,-1,-1):
if nums[i] + i>=n:
n = i
return n ==0
ob1 = Solution()
print(ob1.canJump([2,3,1,1,4]))

Input

[2,3,1,1,4]

Output

True
Updated on 04-May-2020 05:54:49