Jump Game
LeetCode 55 · Medium · solution, intuition & step-by-step walkthrough
Move the goal left whenever i + nums[i] ≥ goal.
This is how I solved Jump Game (LeetCode 55), a medium problem from the Jump / Reachability pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
Approach
- 1
goal = last index.
- 2
For i from right to left: if i + nums[i] ≥ goal, goal = i.
- 3
Return goal == 0.
How I solved it
Greedy backward goalPythonO(n) time · O(1) space
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
goal = n-1
i=n-1
while i>=0:
if nums[i]+i>=goal:
goal = i
i-=1
return goal==0Jump Game — FAQ
What is the intuition behind Jump Game?
Walk backwards keeping a 'goal' — the leftmost index known to reach the end. Any index that can jump to the goal becomes the new goal. If the goal reaches index 0, the start can make it.
How do you solve Jump Game (LeetCode 55)?
1. goal = last index. 2. For i from right to left: if i + nums[i] ≥ goal, goal = i. 3. Return goal == 0.
What is the time and space complexity of Jump Game?
Time: O(n). Space: O(1). (Accepted approach: Greedy backward goal.)
What are common mistakes in Jump Game?
A zero only matters if nothing before it can jump past it.