class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
minStepToIdx = [10001] * n
minStepToIdx[0] = 0
for i in range(n):
for j in range(1, nums[i] + 1):
if i + j < n:
minStepToIdx[i + j] = min(minStepToIdx[i + j], minStepToIdx[i] + 1)
return minStepToIdx[n - 1]
Time Complexity: O(N!) // Loop N times * value of nums[i]
Space Complexity: O(N)
class Solution:
def jump(self, nums: List[int]) -> int:
def dfs(pos):
if pos >= len(nums) - 1:
return 0
minStepJump = 10001
for jump in range(1, nums[pos] + 1):
minStepJump = min(minStepJump, 1 + dfs(pos + jump))
return minStepJump
ans = dfs(0)
return ans
Time Complexity: O(N!)
Space Complexity: O(N) // Recursive call stack of tree height O(N)
Time Complexity: O(N^2)
Space Complexity: O(N)
Time Complexity: O(N^2)
Space Complexity: O(N)
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
maxReachableIdx = 0
lastJumpedPos = 0
jumpStepCnt = 0
for i in range(n - 1):
# We are already able to jump to the end (n-1) position
if lastJumpedPos >= n - 1:
break
# Furthest idx reachable from current level
maxReachableIdx = max(maxReachableIdx, i + nums[i])
# Greedy update (We must jump from the potential position that let us reach the furthest idx)
if i == lastJumpedPos:
lastJumpedPos = maxReachableIdx
jumpStepCnt += 1
return jumpStepCnt
Time Complexity: O(N)
Space Complexity: O(1)
Time Complexity: O(N)
Space Complexity: O(1)