Jump Game - Problem

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 & Output

Example 1 — Basic Case
$ Input: nums = [2,3,1,1,4]
Output: true
💡 Note: Jump 1 step from index 0 to 1, then 3 steps to the last index. Or jump 2 steps from index 0 to 2, then 1 step to index 3, then 1 step to the last index.
Example 2 — Impossible Case
$ Input: nums = [3,2,1,0,4]
Output: false
💡 Note: You will always arrive at index 3. Its maximum jump length is 0, so you cannot proceed further to reach the last index.
Example 3 — Single Element
$ Input: nums = [0]
Output: true
💡 Note: Already at the last index, no jumping needed.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Jump Game - Greedy Algorithm INPUT nums = [2, 3, 1, 1, 4] 0 1 2 3 4 2 3 1 1 4 START GOAL Possible Jumps: max 2 max 3 Each value shows max jump distance from position Goal: Reach index 4 ALGORITHM STEPS 1 Initialize maxReach maxReach = 0 (start pos) 2 Iterate through array For each index i from 0 to n-1 3 Update maxReach maxReach = max(maxReach, i + nums[i]) 4 Check conditions If i > maxReach: return false If maxReach >= n-1: return true Greedy Trace: i=0: max(0, 0+2) = 2 i=1: max(2, 1+3) = 4 4 >= 4 (last idx) Early exit: return true! (no need to check i=2,3,4) FINAL RESULT Winning Path Found: 2 3 1 1 4 Output: true OK - Reachable! Path: 0 --> 1 --> 4 Time: O(n) | Space: O(1) Greedy - single pass! Key Insight: The greedy approach tracks the maximum reachable index at each step. If at any position i, i exceeds maxReach, we're stuck. Otherwise, we update maxReach = max(maxReach, i + nums[i]). We can return true early as soon as maxReach >= last index. No need for backtracking or DP! TutorialsPoint - Jump Game | Greedy Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
78.0K Views
High Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen