Photo by ThisisEngineering RAEng on Unsplash
LeetCode Top 150 Interview Questions-Medium level-#55 Jump Game-Java Python Solutions-TC:O(N) SC:O(1)
Table of contents
Intuition
Check if current index is further than reach
Approach
Init reach to be 0 - Loop through
nums
Check if
index>reach
If so, return
false
- Update reach to be the max between(i+nums[i], reach)
- Returntrue
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
public boolean canJump(int[] nums) {
int reach = 0;
int n = nums.length;
for (int i =0; i<n; i++){
if (i>reach)
return false;
reach = Math.max(reach,i+nums[i]);
}
return true;
}
}
class Solution:
def canJump(self, nums: List[int]) -> bool:
reach=0
for i in range(len(nums)):
if i>reach:
return False
reach=max(reach,i+nums[i])
return True