πDay 13. Minimum Jumps π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given an array arr[]
of non-negative integers, each element represents the maximum number of steps that can be taken forward from that index.
Find the minimum number of jumps required to reach the last index.
If the last index is not reachable, return -1
.
π Example Walkthrough:
Example 1:
Input:
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
Output:
3
Explanation:
Jump from
arr[0] = 1
βarr[1] = 3
.Jump from
arr[1] = 3
βarr[4] = 9
.Jump from
arr[4] = 9
β last index.
Example 2:
Input:
arr = [1, 4, 3, 2, 6, 7]
Output:
2
Explanation:
Jump from
arr[0] = 1
βarr[1] = 4
.Jump from
arr[1] = 4
β last index.
Example 3:
Input:
arr = [0, 10, 20]
Output:
-1
Explanation:
Since arr[0] = 0
, we cannot move forward.
Constraints:
$2 \leq \text{arr.size()} \leq 10^4$
$0 \leq \text{arr[i]} \leq 10^4$
π― My Approach:
Greedy Approach
Track the farthest position reachable at every step.
Use a variable
end
to mark the last index reachable within the current jump.If
i
reachesend
, make a jump and updateend
.If at any point
i == end
andend < n-1
, return-1
.
Algorithm Steps:
Initialize three variables:
jumps = 0
β Tracks the number of jumps.farthest = 0
β Tracks the farthest reachable index.end = 0
β Marks the end of the current jump.
Iterate through the array (except the last element):
Update
farthest = max(farthest, i + arr[i])
.If
i == end
:Increase
jumps
.Update
end = farthest
.If
end >= n-1
, returnjumps
.
If the last index is never reached, return
-1
.
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N)
, as we iterate through the array only once.Expected Auxiliary Space Complexity:
O(1)
, as we use only a few variables for tracking jumps and indices.
π Solution Code
Code (C++)
class Solution {
public:
int minJumps(vector<int>& arr) {
int n = arr.size(), jumps = 0, farthest = 0, end = 0;
if (n == 1) return 0;
for (int i = 0; i < n - 1; i++) {
farthest = max(farthest, i + arr[i]);
if (i == end) {
jumps++;
end = farthest;
if (end >= n - 1) return jumps;
}
}
return -1;
}
};
Code (Java)
class Solution {
static int minJumps(int[] arr) {
int n = arr.length, jumps = 0, farthest = 0, end = 0;
if (n == 1) return 0;
for (int i = 0; i < n - 1; i++) {
farthest = Math.max(farthest, i + arr[i]);
if (i == end) {
jumps++;
end = farthest;
if (end >= n - 1) return jumps;
}
}
return -1;
}
}
Code (Python)
class Solution:
def minJumps(self, arr):
n, jumps, farthest, end = len(arr), 0, 0, 0
if n == 1: return 0
for i in range(n - 1):
farthest = max(farthest, i + arr[i])
if i == end:
jumps += 1
end = farthest
if end >= n - 1: return jumps
return -1
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated