Jump game – LeetCode Solution [Medium]

Problem

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.

LeetCode Problem Link

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.
Approach

Iterate over the array and keep updating a variable maxJump which stores the maximum index we could reach so far. For instance:

nums = [2,3,1,1,4]
maxJump = 0;
for i = 0 to n-1:
  maxJump = max(maxJump, i+nums[i])

Dry run:
i=0: maxJump = 2
i=1: maxJump = 4
i=2: maxJump = 4
i=3: maxJump = 4
i=4: maxJump = 8

Base case:
// We cannot move forward. So we couldn’t reach the last index.
if i > maxJump:  
  return false

Time complexity: O(n), n is the number of elements in array.

Code Implementation

    bool canJump(vector<int>& nums) {
        int n = nums.size();
        int maxJump = 0 + nums[0];
        
        for(int i=0; i<n; i++) {
            if (i > maxJump) {
                return false;
            }
            maxJump = max(maxJump, i+nums[i]);
        } 
        
        return true;
    }

Practice problems
Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *