Jump Game
To solve this coding challenge, you need to determine whether it's possible to jump from the first index to the last index in an array, where each element in the array represents the maximum jump length from that position. The solution involves checking whether each position can be reached based on the maximum distance that can be jumped from previous positions.
Explanation
The main idea is to keep track of the farthest position that can be reached while iterating through the array. If, at any index, the farthest position is less than the current index, it means you cannot proceed further to reach the last index, and the answer is false. On the other hand, if you can reach or surpass the last index, the answer is true. Here's a step-by-step explanation:-
Initialize a variable
max_reachable
-
Iterate through the array
using a loop. The loop variable
i
-
For each index
i
max_reachable
false
-
Update the
max_reachable
i + nums[i]
-
If at any point,
max_reachable
true
-
If the loop completes, return
false
- Initialization :
-
max_reachable
-
The length of the array (
length
- Loop Through Elements :
- The loop runs from the start of the array to the second-to-last index because we're considering jumps from each position.
- Check Unreachable Index :
-
If at any position
i
i
max_reachable
i
false
- Update Maximum Reachable Index :
-
At each index,
max_reachable
i + nums[i]
- Check for Last Index Reachability :
-
If
max_reachable
length - 1
true
- Return Final Verdict :
-
If the loop completes and no early return was triggered, it means you were unable to reach the last index from any of the jumps, hence return
false
Detailed Steps in Pseudocode
# Define a function that takes in an array of integers named nums
function canReachLastIndex(nums):
# Initialize the maximum reachable index at the beginning as 0
max_reachable = 0
# Get the length of the nums array
length = length of nums
# Loop through each index in the nums array
for i from 0 to length - 1:
# If current index is greater than the maximum reachable index
if i > max_reachable:
# You can't reach this index, return false
return false
# Update max_reachable to be the farthest point you can reach from here
max_reachable = maximum of (max_reachable, i + nums[i])
# If max_reachable is beyond or at the last index
if max_reachable >= length - 1:
# You can reach the last index, return true
return true
# If you complete the loop and haven't reached the end, return false
return false
To help reinforce the logic applied: