55. Jump Game (Leetcode || Java || Medium)

Palakkgoyal
2 min readOct 19, 2022

--

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.

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 105

SOLUTION:

class Solution {
public boolean canJump(int[] nums) {
boolean ans = true;//declaring variable to return

//if the first element is 0 then we can’t move from our place
if(nums[0] == 0 && nums.length > 1){
return false;
}

for(int i = 0; i < nums.length; i++){

//if the element we are currently on is directly let us jump to the last index return true and end the question
if(nums[i] + i == nums.length — 1){
return ans;
}

if(nums[i] == 0){//if element is 0, it means that we can’t move from that element. Hence, we will move in the backward direction. If the element that are back can move us one or more steps ahead of the 0 element index then it means that we can move forward from the 0 element
for(int j = i — 1; j >= 0; j — ){
if(nums[j] + j > i){
ans = true;
break;
}else{
ans = false;
}
}

//After the loop if we still are not able to move ahead the 0 element then it means that we can’t reach the last index
if(ans == false){
return false;
}
}
}

return ans;
}
}

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet