Top Interview 150
Navigating through arrays with restrictions is a common challenge in coding interviews. LeetCode 55: Jump Game asks whether you can reach the last index of an array given specific jump constraints. Letβs dive into the problem and solve it efficiently.
π Problem Description
You are given an integer array nums
.
Each element in nums[i]
represents the maximum jump length you can take from that position.
Starting at index 0
, determine if you can reach the last index.
π‘ Examples
Example 1
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step to index 1, then 3 steps to the last index.
Example 2
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always stop at index 3, as its maximum jump length is 0.
π JavaScript Solution
The key to solving this problem is to track the farthest index you can reach while traversing the array. If the farthest index is greater than or equal to the last index, you can reach the end.
Greedy Algorithm
var canJump = function(nums) {
let farthest = 0;
for (let i = 0; i < nums.length; i++) {
if (i > farthest) return false;
farthest = Math.max(farthest, i + nums[i]);
if (farthest >= nums.length - 1) return true;
}
return false;
};
π How It Works
- Track the farthest index: At each step, calculate the maximum index you can reach based on your current position and jump length.
- Check for blockage: If you ever reach an index that exceeds the farthest reachable index, return false.
- Early exit: If the farthest reachable index is greater than or equal to the last index, return true.
π Complexity Analysis
- > Time Complexity:
O(n)
, where n is the length of the array. The array is traversed 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
- Explain edge cases: Discuss scenarios like:
- Single-element array
([0] β true)
. - All zeros except the start
([0,0,0] β false)
.
- Single-element array
- Highlight efficiency: Emphasize the
O(n)
time complexity of the greedy solution. - Alternate approaches: Be ready to discuss solutions like dynamic programming for conceptual depth.
π Learn More
Check out the full explanation and code walkthrough on my Dev.to post:
π Best Time to Buy and Sell Stock II - JavaScript Solution
How would you approach this problem? Letβs discuss below! π
Top comments (0)