Tutorialspoint
Problem
Solution
Submissions

Jump Game

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

Write a C program to determine if you can reach the last index of an array. You are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index.

Example 1
  • Input: nums = [2, 3, 1, 1, 4]
  • Output: true
  • Explanation:
    • Step 1: Start at position 0 with a jump capability of 2.
    • Step 2: From position 0, you can jump to positions 1 or 2.
    • Step 3: Choose to jump to position 1, which has a value of 3.
    • Step 4: From position 1, you can jump to positions 2, 3, or 4.
    • Step 5: Choose to jump to position 4, which is the last index.
    • Step 6: Since you can reach the last index, return true.
Example 2
  • Input: nums = [3, 2, 1, 0, 4]
  • Output: false
  • Explanation:
    • Step 1: Start at position 0 with a jump capability of 3.
    • Step 2: From position 0, you can jump to positions 1, 2, or 3.
    • Step 3: No matter which position you jump to (1, 2, or 3), you will eventually reach position 3.
    • Step 4: At position 3, the jump capability is 0, meaning you cannot move further.
    • Step 5: Since you cannot reach the last index (position 4), return false.
Constraints
  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
  • Time Complexity: O(n), where n is the length of the array
  • Space Complexity: O(1)
ArraysNumberIBMAdobe
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

  • Instead of checking every possible jump combination, use a greedy approach.
  • Keep track of the furthest position you can reach from your current position.
  • As you iterate through the array, update the furthest position you can reach.
  • If at any point, your current position exceeds the furthest position you can reach, return false.
  • If the furthest position you can reach is greater than or equal to the last index, return true.

Steps to solve by this approach:

 Step 1: Initialize the maximum reachable position to 0.

 Step 2: Iterate through the array from left to right.
 Step 3: Check if the current position is reachable from the start.
 Step 4: Calculate the furthest position that can be reached from current index.
 Step 5: Update the maximum reachable position if needed.
 Step 6: If the maximum reachable position is at least the last index, return true.
 Step 7: If the loop completes without reaching the end, return false.

Submitted Code :