DEV Community

Cover image for LeetCode Challenge: 55. Jump Game - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

LeetCode Challenge: 55. Jump Game - JavaScript Solution πŸš€

Top Interview 150

Navigating through arrays with restrictions is a common challenge in coding interviews. LeetCode 55: Jump Game asks whether you can reach the last index of an array given specific jump constraints. Let’s dive into the problem and solve it efficiently.


πŸš€ Problem Description

You are given an integer array nums.

Each element in nums[i] represents the maximum jump length you can take from that position.
Starting at index 0, determine if you can reach the last index.


πŸ’‘ Examples

Example 1

Input: nums = [2,3,1,1,4]  
Output: true  
Explanation: Jump 1 step to index 1, then 3 steps to the last index.
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: nums = [3,2,1,0,4]  
Output: false  
Explanation: You will always stop at index 3, as its maximum jump length is 0.
Enter fullscreen mode Exit fullscreen mode

πŸ† JavaScript Solution

The key to solving this problem is to track the farthest index you can reach while traversing the array. If the farthest index is greater than or equal to the last index, you can reach the end.

Greedy Algorithm

var canJump = function(nums) {
    let farthest = 0;

    for (let i = 0; i < nums.length; i++) {
        if (i > farthest) return false;

        farthest = Math.max(farthest, i + nums[i]);

        if (farthest >= nums.length - 1) return true;
    }

    return false;
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Track the farthest index: At each step, calculate the maximum index you can reach based on your current position and jump length.
  2. Check for blockage: If you ever reach an index that exceeds the farthest reachable index, return false.
  3. Early exit: If the farthest reachable index is greater than or equal to the last index, return true.

πŸ”‘ Complexity Analysis

  • > Time Complexity: O(n), where n is the length of the array. The array is traversed once.
  • > Space Complexity: O(1), as no additional data structures are used.

πŸ“‹ Dry Run

Input: nums = [2,3,1,1,4]

Jump Game
Output: true


✨ Pro Tips for Interviews

  1. Explain edge cases: Discuss scenarios like:
    • Single-element array ([0] β†’ true).
    • All zeros except the start ([0,0,0] β†’ false).
  2. Highlight efficiency: Emphasize the O(n) time complexity of the greedy solution.
  3. Alternate approaches: Be ready to discuss solutions like dynamic programming for conceptual depth.

πŸ“š Learn More

Check out the full explanation and code walkthrough on my Dev.to post:
πŸ‘‰ Best Time to Buy and Sell Stock II - JavaScript Solution

How would you approach this problem? Let’s discuss below! πŸš€

JavaScript #LeetCode #CodingInterview #ProblemSolving

Top comments (0)