Jump Game II – Solution & Complexity
1. Understanding the Problem
- From index
iyou may jump to any index up toi + nums[i]. - You always start at index
0and are guaranteed to reach the end. - We want the fewest jumps to land on the last index.
2. Thinking in Levels (Implicit BFS)
- Group indices by how many jumps it takes to first reach them.
- Level 0 is just index
0; level 1 is everything reachable in one jump, and so on. - The answer is the level number of the last index — exactly a shortest-path / BFS idea, done greedily.
3. Tracking the Current Jump's Reach
endmarks the farthest index covered by the current number of jumps.farthestis the best index reachable while scanning the current level.- When
ireachesend, we have exhausted this level and must take another jump.
4. The Greedy Scan
- Iterate up to the second-to-last index (reaching it is enough).
- Continuously extend
farthest. Wheni == end, incrementjumpsand pushendout tofarthest. - This guarantees the minimum count because each jump greedily covers as far as possible.
5. Complexity
- Time:
O(n)with a single pass over the array. - Space:
O(1)extra. - A single element array needs
0jumps, which the loop naturally returns.