I was working on Jump Game problem on leetcode
Question
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
My Solution
// TC: O(N^2)
// SC: O(1)
var canJump = function(nums) {
let targetIndex = nums.length -1;
//We find the left most element (say 'x') which jumps to last element
//Then we find the left most element that jumps to the above left most element 'x'
while(targetIndex > 0){
//Starting from left find the 1st elements that jumps to target element
for(let i = 0; i < targetIndex; i++){
//If element found update the target element as current index
if(i + nums[i] >= targetIndex){
targetIndex = i
break
}
//If element previous to target element is also not valid than we don't have a solution
if(i === targetIndex -1) return false
}
}
return true
};
Wanted to clarify few things:
- Is this a valid solution? It passes all the test cases on LC however I wanted to confirm my logic as I couldn't find any similar solution in answers.
- Are the mentioned time and space complexities, \$O(N^2)\$ & \$O(1)\$ respectively correct?
- If the solution is correct, what would call this approach? Is it greedy or dynamic programming? I don't understand the difference between the 2 right now.