Skip to content

Commit f47fae4

Browse files
committed
refactor(algorithms, greedy): jump game 2 alternative solution
1 parent 709afbe commit f47fae4

22 files changed

+168
-52
lines changed

algorithms/greedy/jump_game/README.md

Lines changed: 101 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -22,44 +22,6 @@ Explanation: You will always arrive at index 3 no matter what. Its maximum jump
2222
to reach the last index.
2323
```
2424

25-
---
26-
27-
## Jump Game II
28-
29-
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
30-
31-
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at
32-
nums[i], you can jump to any nums[i + j] where:
33-
34-
0 <= j <= nums[i] and
35-
i + j < n
36-
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach
37-
nums[n - 1].
38-
39-
```text
40-
Example 1:
41-
42-
Input: nums = [2,3,1,1,4]
43-
Output: 2
44-
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
45-
the last index.
46-
```
47-
48-
```text
49-
Example 2:
50-
51-
Input: nums = [2,3,0,1,4]
52-
Output: 2
53-
```
54-
55-
---
56-
57-
## Topics
58-
59-
- Array
60-
- Dynamic Programming
61-
- Greedy
62-
6325
## Solutions
6426

6527
1. [Naive Approach](#naive-approach)
@@ -140,3 +102,104 @@ elements in the array.
140102
#### Space Complexity
141103

142104
The space complexity of the above solution is O(1), because we do not use any extra space.
105+
106+
107+
---
108+
109+
# Jump Game II
110+
111+
You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].
112+
113+
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at
114+
nums[i], you can jump to any nums[i + j] where:
115+
116+
0 <= j <= nums[i] and
117+
i + j < n
118+
Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach
119+
nums[n - 1].
120+
121+
```text
122+
Example 1:
123+
124+
Input: nums = [2,3,1,1,4]
125+
Output: 2
126+
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
127+
the last index.
128+
```
129+
130+
```text
131+
Example 2:
132+
133+
Input: nums = [2,3,0,1,4]
134+
Output: 2
135+
```
136+
137+
![Example 1](./images/examples/jump_game_2_example_1.png)
138+
![Example 2](./images/examples/jump_game_2_example_2.png)
139+
![Example 3](./images/examples/jump_game_2_example_3.png)
140+
![Example 4](./images/examples/jump_game_2_example_4.png)
141+
![Example 5](./images/examples/jump_game_2_example_5.png)
142+
![Example 6](./images/examples/jump_game_2_example_6.png)
143+
144+
## Solution
145+
146+
We’ll solve this problem using a greedy approach. At each step, we choose the jump that allows us to reach the farthest
147+
point. The objective is to minimize the number of jumps required to reach the end of the array. This strategy is
148+
considered greedy because it selects the best possible move at each step without considering the impact on future jumps.
149+
By always jumping as far as possible, we cover more distance and use fewer jumps to reach the end.
150+
151+
To find the minimum number of jumps needed to reach the end of the array, keep track of how far you can go with the
152+
current number of jumps. As you progress through the array, update this maximum reach based on your current position.
153+
When you reach the limit of your current jump range, increase your jump count and adjust the range to the farthest
154+
position you can reach with the next jump. Continue this process until you reach or exceed the end of the array.
155+
156+
The steps of the algorithm are given below:
157+
158+
1. Initialize three variables, all set to 0.
159+
- `jumps`: This variable tracks the minimum number of jumps required to reach the end of the array and will be
160+
returned as the final output.
161+
- `current_jump_boundary`: This represents the maximum index we can reach with the current number of jumps. It acts
162+
as the boundary of how far we can go before making another jump.
163+
- `farthest_jump_index`: This tracks the farthest index we can reach from the current position by considering all
164+
possible jumps within the current jump’s range.
165+
166+
2. Iterate through the nums array and perform the following steps:
167+
- Update `farthest_jump_index`: For each index i, calculate i + nums[i], which represents the farthest index we can
168+
reach from i. Update farthest_jump_index to be the maximum of its current value and i + nums[i].
169+
- Check if a new jump is needed: If i equals current_jump_boundary, it means we’ve reached the limit of the current
170+
jump. Increment jumps by 1, and update current_jump_boundary to farthest_jump_index to set up for the next jump.
171+
172+
3. After iterating through the array, jumps will contain the minimum number of jumps needed to reach the end. Return
173+
this value as the output.
174+
175+
Let’s look at the following illustration to get a better understanding of the solution:
176+
177+
![Solution 1](./images/solutions/jump_game_2_solution_1.png)
178+
![Solution 2](./images/solutions/jump_game_2_solution_2.png)
179+
![Solution 3](./images/solutions/jump_game_2_solution_3.png)
180+
![Solution 4](./images/solutions/jump_game_2_solution_4.png)
181+
![Solution 5](./images/solutions/jump_game_2_solution_5.png)
182+
![Solution 6](./images/solutions/jump_game_2_solution_6.png)
183+
![Solution 7](./images/solutions/jump_game_2_solution_7.png)
184+
![Solution 8](./images/solutions/jump_game_2_solution_8.png)
185+
![Solution 9](./images/solutions/jump_game_2_solution_9.png)
186+
![Solution 10](./images/solutions/jump_game_2_solution_10.png)
187+
![Solution 11](./images/solutions/jump_game_2_solution_11.png)
188+
![Solution 12](./images/solutions/jump_game_2_solution_12.png)
189+
![Solution 13](./images/solutions/jump_game_2_solution_13.png)
190+
191+
### Time Complexity
192+
193+
The time complexity of the above solution is O(n), where n is the length of nums because we are iterating the array once.
194+
195+
### Space Complexity
196+
197+
The space complexity of the above solution is O(1), because we are not using any extra space.
198+
199+
---
200+
201+
# Topics
202+
203+
- Array
204+
- Dynamic Programming
205+
- Greedy

algorithms/greedy/jump_game/__init__.py

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ def can_jump(nums: List[int]) -> bool:
2222

2323
return True
2424

25+
2526
def can_jump_2(nums: List[int]) -> bool:
2627
"""
2728
This function checks if it is possible to reach the last index of the array from the first index.
@@ -46,7 +47,18 @@ def can_jump_2(nums: List[int]) -> bool:
4647

4748

4849
def jump(nums: List[int]) -> int:
50+
"""
51+
This function returns the minimum number of jumps needed to reach the last index of the array from the first index.
52+
Args:
53+
nums(list): list of integers
54+
Returns:
55+
int: minimum number of jumps needed to reach the last index
56+
"""
4957
size = len(nums)
58+
# if start index == destination index == 0
59+
if size == 1:
60+
return 0
61+
5062
# destination is last index
5163
destination = size - 1
5264

@@ -56,10 +68,6 @@ def jump(nums: List[int]) -> int:
5668
# min number of jumps
5769
min_jumps = 0
5870

59-
# if start index == destination index == 0
60-
if size == 1:
61-
return 0
62-
6371
# Greedy strategy: extend coverage as long as possible with lazy jump
6472
for idx in range(size):
6573
# extend coverage as far as possible
@@ -78,3 +86,42 @@ def jump(nums: List[int]) -> int:
7886
return min_jumps
7987

8088
return min_jumps
89+
90+
91+
def jump_2(nums: List[int]) -> int:
92+
"""
93+
This function returns the minimum number of jumps needed to reach the last index of the array from the first index.
94+
Args:
95+
nums(list): list of integers
96+
Returns:
97+
int: minimum number of jumps needed to reach the last index
98+
"""
99+
# Store the length of the input array
100+
size = len(nums)
101+
102+
# if start index == destination index == 0
103+
if size == 1:
104+
return 0
105+
106+
# Initialize the variables to track the number of jumps,
107+
# the current jump's limit, and the farthest reachable index
108+
min_jumps = 0
109+
current_jump_boundary = 0
110+
furthest_jump_index = 0
111+
112+
# Iterate through the array, stopping before the last element
113+
for idx in range(size - 1):
114+
# Update the farthest_jump_index to be the maximum of its current value
115+
# and the index we can reach from the current position
116+
furthest_jump_index = max(furthest_jump_index, idx + nums[idx])
117+
118+
# If we have reached the limit of the current jump
119+
if idx == current_jump_boundary:
120+
# update counter of jump by +1
121+
min_jumps += 1
122+
123+
# Update the current_jump_boundary to the farthest we can reach
124+
current_jump_boundary = furthest_jump_index
125+
126+
# Return the total number of jumps needed to reach the end of the array
127+
return min_jumps
72.5 KB
Loading
71.6 KB
Loading
65.6 KB
Loading
76.6 KB
Loading
77.8 KB
Loading
69 KB
Loading
54 KB
Loading
46.8 KB
Loading

0 commit comments

Comments
 (0)