#45
Jump Game II
MediumArrayDynamic ProgrammingGreedyGreedyDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach to minimize the number of jumps. Instead of exploring all paths, it keeps track of the farthest point reachable with the current number of jumps and updates the jump count accordingly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize variables for the current end of the jump range and the farthest reachable index.
- 2Step 2: Iterate through the array, updating the farthest index reachable from the current position.
- 3Step 3: When reaching the end of the current jump range, increment the jump count and update the current end to the farthest index.
solution.py10 lines
1def jump(nums):
2 jumps = 0
3 current_end = 0
4 farthest = 0
5 for i in range(len(nums) - 1):
6 farthest = max(farthest, i + nums[i])
7 if i == current_end:
8 jumps += 1
9 current_end = farthest
10 return jumpsℹ
Complexity note: This complexity is linear because we only make a single pass through the array, updating our jump count and farthest index without any nested loops.
- 1The greedy approach significantly reduces the number of computations by focusing on the farthest reachable index.
- 2Understanding the problem as a series of intervals can help visualize the jumps needed.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.