45. Jump Game II
Problem¶
You are given a 0-indexed array of integers nums
of length n
. You are initially positioned at nums[0]
.
Each element nums[i]
represents the maximum length of a forward jump from index i
. In other words, if you are at nums[i]
, you can jump to any nums[i + j]
where:
0 <= j <= nums[i]
andi + j < n
Return the minimum number of jumps to reach nums[n - 1]
. The test cases are generated such that you can reach nums[n - 1]
.
Example 1:
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [2,3,0,1,4]
Output: 2
Constraints:
1 <= nums.length <= 10**4
0 <= nums[i] <= 1000
- It’s guaranteed that you can reach
nums[n - 1]
.
Solve¶
Water falling¶
O(n)
Following a minimized greedy/dynamic programming minimized path problem from graph.
- Calling the
minimum
array is to store the total minimal step needed to reach each element,minimum[i]
correspond toelement[i]
. At first,minimum
array isn’t set, as none element is being processed. - We start at
index=0
, coststep=0
jump step. As we already start at the first element. This also mean we haveminimum[0] = 0
- From next, we start a loop
- We find a element with index
pos
that have minimumstep
value, that is not visited/process - Flag it as already visited
- Update all other element our current
pos
can jump into new minimum (step + 1
) if it either uninitialized or it currently have a less optimal total of step need to jump into.
- We find a element with index
This is when I also realized we dealing with a serial of number, a special case of graph data:
- The minimum jump step to each element isn’t change value after initialized.
So that mean we can just skip most of the unnecessary loop to update the
minimum
.
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
p = 0
minimum = [-1] * n
minimum[0] = 0
q = [(0, 0)]
while q:
pos, step = q.pop(0)
for npos in range(p, min(n, pos + nums[pos]+1)):
if minimum[npos] == -1:
minimum[npos] = step + 1
q.append((npos, step + 1))
p = npos
return minimum[-1]
So I calling it water fall basically because the height being collapsing all at once (this is visualization process on white board)
Time complexity: O(n)
- BFS: Each
minimum
is updated once, visited once; - DP update loop: By updating temporary
p
pointer, the nested loop only run in total n times independent with the total time BFS queue call (thus not our time complexity isn’t multiple to O(n^2) ).
Created : August 16, 2023