File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 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 ]
You can’t perform that action at this time.
0 commit comments