30 Days of LeetCode: Day 9 - The Jump Game

30 Days of LeetCode: Day 9 - The Jump Game

Today's LeetCode challenge taught me an important lesson about the gap between understanding a problem and implementing it correctly. While I grasped about 70% of the core concepts, my solution revealed some crucial misunderstandings about how to implement them.

The Challenge

Given an array where each number represents the maximum jump length from that position, determine if you can reach the last index starting from the first position.

Example:

Input: nums = [2,3,1,1,4]
Output: true
// Can jump 1 step from index 0 to 1, then 3 steps to the last index

My Initial Approach

I understood that we needed to track our position and check distances to the end. My solution treated zeros as automatic stopping points and assumed we had to jump the exact number of spaces shown in each position:

var canJump = function(nums) {
    if (nums.length == 1) return true;

    let spaceToEnd;
    let keepJumping;

    for(let i = 0; i < nums.length; i++) {
        (nums[i] == 0) ? keepJumping = false : keepJumping = true;
        if (keepJumping) {
            spaceToEnd = nums.length - i;
        }
    }
    return spaceToEnd < 0;
};

Where I went wrong was not realizing that:

  1. If we see a 2, we can jump 1 OR 2 spaces (not exactly 2)

  2. A zero isn't always a problem if we can jump over it

The Correct Solution

var canJump = function(nums) {
    let maxReach = 0;  // Track furthest reachable position

    for(let i = 0; i <= maxReach; i++) {
        // Update furthest reachable position
        maxReach = Math.max(maxReach, i + nums[i]);

        // Can we reach the end?
        if(maxReach >= nums.length - 1) return true;
    }

    return false;
};

Key Learnings

  1. Maximum vs Exact: Values represent maximum jump distances, not required distances

  2. Reachability: Need to track what positions are actually reachable

  3. Position Tracking: Focus on what's reachable, not where we must land

Tomorrow brings another challenge, but today's lesson is really making me realize a trending theme in how i approach problems- make the solution simple!