i
allows a jump of up to nums[i]
steps.i
, we can jump to indices i+1
, i+2
, ..., up to i+nums[i]
.can_reach(i)
that returns True
if we can reach the last index from i
, otherwise False
.i == n-1
), we’ve reached the target, so return True
.i
, try all possible jumps (from 1 to nums[i]
).can_reach(i+jump)
. If any jump leads to the last index (returns True
), return True
.False
.can_reach(0)
to check if we can reach the last index from the start.
memo
to store whether each index can reach the last index (True
or False
).memo[n-1] = True
since the last index is the target.can_reach(i)
to check if index i
is in memo
. If so, return the cached result.nums[i]
and recursively call can_reach(i+jump)
.True
, store memo[i] = True
and return True
.memo[i] = False
and return False
.can_reach(0)
to start from the first index.memo
dictionary and recursion stack.
target
as the last index (n-1
), the goal we need to reach.n-2
) to 0.i
, check if it can reach the current target
by verifying if i + nums[i] >= target
.target
to i
, as we now need to reach index i
to get to the last index.target == 0
, it means we can reach the last index starting from index 0.target != 0
, it’s impossible to reach the last index.
The Jump Game is a popular algorithmic problem that asks whether it's possible to reach the last index of an array starting from the first index. Each element in the array represents your maximum jump length from that position. This problem tests your understanding of dynamic programming and greedy algorithms, and is frequently featured in technical interviews.
The brute-force method for solving the Jump Game is to simulate every possible jump path recursively. From each index, you attempt all jumps from 1 up to nums[i]
. If any path eventually leads to the last index, the function returns true.
While intuitive, this approach has poor performance due to redundant calculations and an exponential number of paths. It becomes impractical for large input arrays.
A far more efficient approach to the Jump Game is to use a greedy algorithm. Instead of exploring all paths, you keep track of the leftmost position from which the last index can be reached. You iterate backward through the array and update this "target" index whenever you find a position from which the target is reachable.
If by the end of the loop the target reaches index 0, it means the first index can reach the end.
target = n - 1
(the last index).i = n - 2
down to 0.i + nums[i] >= target
. If so, set target = i
.target == 0
, return true; else, return false.The Jump Game demonstrates the power of greedy algorithms in optimizing problems that would otherwise involve exponential backtracking. By scanning backward and greedily updating the reachable index, we eliminate unnecessary computation and deliver an optimal O(n) solution. Mastering this pattern can help tackle a wide range of reachability and dynamic programming challenges.