Algorithm Day79 - Jump Game
π§© Problem Description
You are given an integer array nums. You are initially positioned at the 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.
π¬ Examples
Example 1
1 | Input: nums = [2,3,1,1,4] |
Example 2
1 | Input: nums = [3,2,1,0,4] |
π‘ Intuition
We need to check whether itβs possible to reach the last index:
- Keep track of the farthest position reachable while traversing the array.
- If at any index
i,i > farthest, then we cannot reach this index β return false. - Otherwise, update
farthest = max(farthest, i + nums[i]). - If the farthest index is at least the last index, return true.
This is a classic greedy approach.
π’ Java Code (Greedy)
1 | class Solution { |
β± Complexity Analysis
- Time: O(n) β single pass.
- Space: O(1).
βοΈ Summary
- Maintain the farthest index reachable while iterating.
- If you ever get stuck (
i > farthest), return false. - Greedy solution ensures linear time complexity.
Related problems
lc-45β Jump Game IIlc-1306β Jump Game IIIlc-1345β Jump Game IV