This is LeetCode #55: Jump Game — a classic greedy problem! 🦘
💡 Think of it like this: You're standing on stepping stones. Each stone has a number that tells you the MAXIMUM number of stones you can jump forward. Can you reach the last stone?
The Greedy Insight: Keep track of the farthest position you can possibly reach. If at any point your current position is beyond the farthest reachable — you're stuck!
💭 Now it's your turn! Using the approach above, implement your solution in the editor. You've got this! 💪
Step-by-step trace for [2, 3, 1, 1, 4]:
Why Greedy works here: We don't need to find the exact path — we just need to know IF we can reach the end. By tracking the farthest reachable index, we get O(n) time, O(1) space.
def canJump(nums):
farthest = 0
for i in range(len(nums)):
if i > farthest: # Can't reach this position!
return False
farthest = max(farthest, i + nums[i]) # Update how far we can go
return True
canJump([2,3,1,1,4])
True
canJump([3,2,1,0,4])
False