Top Interview 150
Jumping through arrays with minimal effort is a classic problem that challenges your algorithmic thinking. Let's tackle LeetCode 45: Jump Game II, which asks us to find the minimum number of jumps required to reach the last index.
π Problem Description
You are given an integer array nums
of length n
.
Each element nums[i]
represents the maximum length of a forward jump from index π
. Return the minimum number of jumps required to reach nums[n - 1]
. Itβs guaranteed that you can always reach the last index.
π‘ Examples
Example 1
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: 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
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
π JavaScript Solution
To solve this efficiently, we use a greedy approach to minimize the number of jumps by always jumping as far as possible within the current range.
Greedy Algorithm
var jump = function(nums) {
let jumps = 0;
let currentEnd = 0;
let farthest = 0;
for (let i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i === currentEnd) {
jumps++;
currentEnd = farthest;
}
}
return jumps;
};
π How It Works
-
Track the farthest point:
- As we iterate, calculate how far we can reach (farthest) using the current jump.
-
Trigger a jump:
- Whenever we exhaust the range of the current jump
(i === currentEnd)
, increment the jump counter and set the next range to the farthest point.
- Whenever we exhaust the range of the current jump
-
Stop at the last index:
- The loop runs only until
nums.length - 2
, as we donβt need to jump beyond the last index.
- The loop runs only until
π Complexity Analysis
- > Time Complexity:
O(n)
, where n is the length of the array. We traverse the array once. - > Space Complexity:
O(1)
, as no additional data structures are used.
π Dry Run
Input: nums = [2,3,1,1,4]
β¨ Pro Tips for Interviews
- Understand the greedy choice: Explain why jumping to the farthest reachable index minimizes total jumps.
- Clarify constraints: Confirm with the interviewer that reaching the last index is always possible.
- Edge cases:
- Single-element array (
[0] β 0 jumps
). - Maximum jump length always greater than or equal to array length.
- Single-element array (
π Learn More
Check out the full explanation and code walkthrough on my Dev.to post:
π Jump Game - JavaScript Solution
Whatβs your approach to solving this problem? Letβs discuss below! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!