Skip to content

Commit 31c9e1e

Browse files
committed
solve: jumpGame
1 parent dce73ca commit 31c9e1e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

jump-game/yolophg.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Time Complexity: O(n) - go through the array once, checking jump reachability.
2+
# Space Complexity: O(1) - no extra space used, just a few variables.
3+
4+
class Solution:
5+
def canJump(self, nums: List[int]) -> bool:
6+
7+
if len(nums) == 1:
8+
# if there's only one element, we're already at the last index
9+
return True
10+
11+
# start from second-to-last index
12+
backtrack_index = len(nums) - 2
13+
# need to jump at least once to reach the last index
14+
jump = 1
15+
16+
while backtrack_index > 0:
17+
# If we can jump from this position to the next "safe" spot
18+
if nums[backtrack_index] >= jump:
19+
# reset jump counter since we found a new reachable point
20+
jump = 1
21+
else:
22+
# otherwise, increase the jump required
23+
jump += 1
24+
25+
# move one step left
26+
backtrack_index -= 1
27+
28+
# finally, check if we can reach the last index from the starting position
29+
return jump <= nums[0]

0 commit comments

Comments
 (0)