You are given an integer array nums. You are initially positioned at the array’s first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which means you cannot move from there.
The problem can be solved using a greedy approach. The idea is to keep track of the farthest index that can be reached as we iterate through the array. If we find any index where the farthest index is less than the current index, it means we can’t proceed further and hence cannot reach the last index.
Steps:
maxReach to 0, which keeps track of the farthest index we can reach.i:
i is greater than maxReach, return false.maxReach to be the maximum of maxReach and i + nums[i].maxReach is greater than or equal to the last index, return true.true.Here is the C++ solution based on the above strategy:
#include <vector>
#include <iostream>
bool canJump(std::vector<int>& nums) {
int maxReach = 0;
for (int i = 0; i < nums.size(); i++) {
if (i > maxReach) {
return false;
}
maxReach = std::max(maxReach, i + nums[i]);
if (maxReach >= nums.size() - 1) {
return true;
}
}
return true;
}
int main() {
std::vector<int> nums1 = {2, 3, 1, 1, 4};
std::vector<int> nums2 = {3, 2, 1, 0, 4};
std::cout << "Example 1: " << (canJump(nums1) ? "true" : "false") << std::endl;
std::cout << "Example 2: " << (canJump(nums2) ? "true" : "false") << std::endl;
return 0;
}
O(n), where n is the length of the array. This is because we are iterating through the array once.O(1) since we are using only a constant amount of extra space regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?