Jump Game II
LeetCode 45 · Medium · solution, intuition & step-by-step walkthrough
Implicit BFS over index windows.
This is how I solved Jump Game II (LeetCode 45), 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
Think in BFS levels: all indices reachable with s jumps form a contiguous window [l, r]. The next window ends at the farthest index any of them can reach. Count windows until the last index is covered.
Approach
- 1
Window [l, r] = indices reachable in steps jumps.
- 2
farthest = max(i + nums[i]) over the window.
- 3
Next window is [r+1, farthest]; steps += 1.
- 4
Stop when r ≥ n − 1.
How I solved it
Greedy BFS windowsPythonO(n) time · O(1) space
class Solution:
def jump(self, nums: List[int]) -> int:
l=0
r=0
n = len(nums)
steps=0
while r<n-1:
farthest=0
for i in range(l,r+1):
farthest=max(farthest,i+nums[i])
l=r+1
r=farthest
steps+=1
return steps
Jump Game II — FAQ
What is the intuition behind Jump Game II?
Think in BFS levels: all indices reachable with s jumps form a contiguous window [l, r]. The next window ends at the farthest index any of them can reach. Count windows until the last index is covered.
How do you solve Jump Game II (LeetCode 45)?
1. Window [l, r] = indices reachable in steps jumps. 2. farthest = max(i + nums[i]) over the window. 3. Next window is [r+1, farthest]; steps += 1. 4. Stop when r ≥ n − 1.
What is the time and space complexity of Jump Game II?
Time: O(n). Space: O(1). (Accepted approach: Greedy BFS windows.)
What are common mistakes in Jump Game II?
Already at the end (n = 1) means 0 jumps.