LC055 - Jump Game

Problem

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example

Input: nums = [2,3,1,1,4]

Output: true

Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Solution

Naive

Evaluate all possible moves using a decision tree. This would be a time complexity of O(nn)O(n^n).

Greedy

Decrement pointer to element that can reach the target (last) element. This algorithm is linear in time, and hence O(n)O(n).

def canJump(self, nums: List[int]) -> bool:
	# target is the index of the last element
	target = len(nums) - 1

	for i in range(len(nums)-1, -1, -1):
		if i + nums[i] >= target:
			target = i

	if target == 0:
		return True
		
	return False

Last updated