Tutorialspoint
Problem
Solution
Submissions

Jump Game

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to determine if you can reach the last index of an array. You are given an integer array nums where each element represents the maximum number of steps you can jump forward from that position. You start at the first index and need to determine if you can reach the last index.

Example 1
  • Input: nums = [2,3,1,1,4]
  • Output: true
  • Explanation:
    • Start at index 0 with value 2, you can jump 1 or 2 steps.
    • Jump 1 step to index 1 (value 3), now you can jump 1, 2, or 3 steps.
    • Jump 3 steps to index 4 (last index), successfully reached the end.
    • Therefore, it's possible to reach the last index.
Example 2
  • Input: nums = [3,2,1,0,4]
  • Output: false
  • Explanation:
    • Start at index 0 with value 3, you can jump 1, 2, or 3 steps.
    • Any jump (1, 2, or 3 steps) leads to indices with decreasing jump values.
    • Eventually you reach index 3 with value 0, making further progress impossible.
    • Therefore, you cannot reach the last index.
Constraints
  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysPwCTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a greedy approach by tracking the farthest reachable position
  • Iterate through the array and update the maximum reachable index at each step
  • At each position, check if the current index is reachable from previous positions
  • If current index is beyond the farthest reachable position, return false
  • Update the farthest reachable position using current index + nums[current index]
  • If at any point the farthest reachable position >= last index, return true

Steps to solve by this approach:

  Step 1: Initialize a variable 'farthest' to track the maximum reachable index, starting at 0.

 Step 2: Iterate through each index of the array from left to right.
 Step 3: At each index, check if the current position is reachable (i <= farthest).
 Step 4: If current index is beyond farthest reachable position, return false immediately.
 Step 5: Update farthest reachable position using Math.max(farthest, current_index + nums[current_index]).
 Step 6: Check if farthest position can reach or exceed the last index, if so return true early.
 Step 7: After the loop, return whether farthest position is greater than or equal to last index.

Submitted Code :