Neetcode 150 - Jump Game
1. Input, Output, Contrains
- Input:
nums = [2,3,1,1,4]
- Output:
True
- Constrains:
-
1 ≤ len(nums) ≤ 10⁵
-
0 ≤ nums[i] ≤ 10⁵
2. Dry run
i nums[i] farthest = max(farthest, i + nums[i]) can reach i? note
0 2 max(0, 0+2)=2 ✅ yes can go up to index 2
1 3 max(2, 1+3)=4 ✅ yes can go to the end
2 1 max(4, 2+1)=4 ✅ yes still within range
3 1 max(4, 3+1)=4 ✅ yes
4 4 max(4, 4+4)=8 ✅ yes end reached
3. Naive Solution O(N^2)
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
reachable = [False] * n
reachable[0] = True
for i in range(n):
if not reachable[i]:
continue
for j in range(1, nums[i] + 1):
if i + j < n:
reachable[i + j] = True
return reachable[-1]
⏱️ Complexity
-
Time: O(N^2)
-
Space: O(N)
4. Optimal Solution — O(N) Greedy
class Solution:
def canJump(self, nums: List[int]) -> bool:
farthest = 0
for i, jump in enumerate(nums):
if i > farthest:
return False
farthest = max(farthest, i + jump)
return True
⏱️ Complexity
-
Time: O(N)
-
Space: O(1)
Last Updated On October 14, 2025