Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Jump Game II | Leetcode 45 | Recursive and Greedy Solution
    Data Structures & Algorithms

    Jump Game II | Leetcode 45 | Recursive and Greedy Solution

    Anirudh KhuranaBy Anirudh Khurana21 August 2025Updated:16 November 2026No Comments8 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to solve jump game 2
    Share
    Facebook Twitter LinkedIn Pinterest Email

    This problem asks: given an array nums where nums[i] is the maximum jump length from index i, find the minimum number of jumps needed to reach the last index. You start at index 0. You can always assume the last index is reachable as per the original LeetCode statement.

    Here’s the [Problem Link] to begin with.

    Contents:
     [show]
    • What does the problem say? (with examples)
    • Solution 1: Simple Recursion
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Time and Space Complexity
      • Conclusion
    • Solution 2: Greedy (Optimal)
      • Intuition and Approach
      • Code Implementation
      • Code Explanation
      • Time and Space Complexity
      • Conclusion
    • Final Takeaway

    What does the problem say? (with examples)

    You need to reach the last index in the fewest jumps.

    Example 1

    Input: nums = [2,3,1,1,4]
    Output: 2
    Explanation: Jump from index 0 -> 1 (length 1), then 1 -> 4 (length 3).

    Example 2

    Input: nums = [2,3,0,1,4]
    Output: 2
    Explanation: 0 -> 1, then 1 -> 4.

    Key insight: you are minimizing the number of jumps, not the distance per jump. Large jumps can be good if they reduce the number of total moves.

    Interactive Visualizer: Greedy Window

    Choose an example or enter your own jump lengths, then press Next. The orange cells are the current window, all the indices reachable with the same number of jumps. Each window ends with one more jump to the farthest index found inside it.



    Solution 1: Simple Recursion

    Intuition and Approach

    A straightforward idea is to try all possible jumps from the current index and choose the minimum among them. From index, you can jump up to nums[index] steps forward. Recursively compute the minimum jumps needed from each reachable next index and take the minimum.

    This is a direct search of the decision tree:

    • Base case: if index is at or beyond the last index, return the number of jumps taken so far.
    • Otherwise, try every jump length from 1 to nums[index] and take the minimum of those results.

    This approach is correct but explores many overlapping subproblems without caching, which makes it very slow on large inputs.

    Code Implementation

    class Solution:
        def solve(self, index, jump, lastIndex, nums):
            if index >= lastIndex:
                return jump
            minJump = float("inf")
            for i in range(1, nums[index] + 1):
                minJump = min(minJump, self.solve(index + i, jump + 1, lastIndex, nums))
            return minJump
    
        def jump(self, nums: List[int]) -> int:
            return self.solve(0, 0, len(nums) - 1, nums)
    class Solution {
        private int solve(int index, int jump, int lastIndex, int[] nums) {
            if (index >= lastIndex) {
                return jump;
            }
            int minJump = Integer.MAX_VALUE;
            for (int i = 1; i <= nums[index]; i++) {
                minJump = Math.min(minJump, solve(index + i, jump + 1, lastIndex, nums));
            }
            return minJump;
        }
    
        public int jump(int[] nums) {
            return solve(0, 0, nums.length - 1, nums);
        }
    }
    class Solution {
        int solve(int index, int jump, int lastIndex, vector<int>& nums) {
            if (index >= lastIndex) {
                return jump;
            }
            int minJump = INT_MAX;
            for (int i = 1; i <= nums[index]; i++) {
                minJump = min(minJump, solve(index + i, jump + 1, lastIndex, nums));
            }
            return minJump;
        }
    
    public:
        int jump(vector<int>& nums) {
            return solve(0, 0, nums.size() - 1, nums);
        }
    };

    Code Explanation

    • solve(index, jump, lastIndex, nums) returns the minimal jumps to reach or pass lastIndex starting from index, given that you have already taken jump jumps.
    • If index >= lastIndex, you are done and return jump.
    • Otherwise, you iterate possible next steps i from 1 to nums[index], recursively compute the answer for index + i, and track the minimum.
    • jump(nums) starts the process from index 0 with 0 jumps.

    Time and Space Complexity

    • Precise: In the worst case, from each index you branch up to nums[index] times and recompute many subproblems repeatedly. This yields exponential time, commonly characterized as worse than O(2^n) for adversarial inputs.
    • Simplified: Exponential time. Not feasible for large arrays.
    • Space: The maximum recursion depth is at most n, so O(n) stack space.

    Conclusion

    Simple recursion is easy to understand but impractical without memoization or other optimizations. It suffers from massive recomputation and will time out on typical test cases.


    Solution 2: Greedy (Optimal)

    Intuition and Approach

    A classic greedy strategy solves this in linear time by viewing the array as levels of reachable indices:

    • Maintain the current window [left, right] of indices you can reach with the current number of jumps.
    • Within this window, compute the farthest index you can reach with one more jump.
    • Move to the next window and increment the jump count.
    • Repeat until the right boundary reaches or passes the last index.

    This is analogous to a breadth-first expansion across indices, but implemented with two pointers and a single pass.

    Code Implementation

    class Solution:
        def jump(self, nums: List[int]) -> int:
            n = len(nums)
            jumps = 0
            left = 0
            right = 0
            while right < n - 1:
                farthest = 0
                for i in range(left, right + 1):
                    farthest = max(farthest, i + nums[i])
                left = right + 1
                right = farthest
                jumps += 1
            return jumps
    class Solution {
        public int jump(int[] nums) {
            int n = nums.length;
            int jumps = 0;
            int left = 0;
            int right = 0;
            while (right < n - 1) {
                int farthest = 0;
                for (int i = left; i <= right; i++) {
                    farthest = Math.max(farthest, i + nums[i]);
                }
                left = right + 1;
                right = farthest;
                jumps++;
            }
            return jumps;
        }
    }
    class Solution {
    public:
        int jump(vector<int>& nums) {
            int n = nums.size();
            int jumps = 0;
            int left = 0;
            int right = 0;
            while (right < n - 1) {
                int farthest = 0;
                for (int i = left; i <= right; i++) {
                    farthest = max(farthest, i + nums[i]);
                }
                left = right + 1;
                right = farthest;
                jumps++;
            }
            return jumps;
        }
    };

    Code Explanation

    • left and right define the current range of indices reachable with jumps jumps.
    • For every index i in the current range, compute how far you can go next as i + nums[i], and track the maximum as farthest.
    • After scanning the range, set the next range to [right + 1, farthest] and increment jumps.
    • The loop stops when right has reached or crossed the last index. The counter jumps is the minimal number of jumps.

    This works because scanning all indices in the current reachable window ensures you consider every possible jump of length jumps + 1 and choose the furthest frontier for the next step, which minimizes the total number of jumps.

    Time and Space Complexity

    • Precise: Each index enters the inner loop exactly once across all iterations, so the total cost is O(n) for the scans plus O(n) for boundary updates, which is O(n + n).
    • Simplified: O(n) time.
    • Space: Only a few variables are used, so O(1) extra space.

    Conclusion

    The greedy window expansion is the optimal approach. It runs in linear time, uses constant space, and reliably computes the minimal number of jumps by expanding the furthest reachable frontier at each step.


    Final Takeaway

    • Simple recursion explores all choices and is correct but exponential in time.
    • The greedy window method is optimal, achieving O(n) time and O(1) space by expanding the reachable range level by level and counting how many expansions are needed.

    Frequently Asked Questions

    What is Jump Game II?

    You are given an array where nums[i] is the maximum jump length from index i. Starting at index 0, return the minimum number of jumps needed to reach the last index. The problem guarantees the last index is reachable. For [2,3,1,1,4] the answer is 2.

    Why does the greedy solution give the minimum number of jumps?

    It works like breadth-first search. The window [left, right] holds every index reachable with the current number of jumps, and the farthest point reachable from that window becomes the next window. Since each window is the full set for that jump count, the first window that contains the last index gives the minimum.

    What is the time and space complexity of Jump Game II?

    The greedy solution visits each index once, so it runs in O(n) time with O(1) extra space. The simple recursive solution tries every jump from every index, which is exponential.

    Can Jump Game II be solved with dynamic programming?

    Yes. A DP array where dp[i] is the minimum jumps to reach i works in O(n²) time. The greedy window gives the same answer in O(n), so it is the expected interview solution.

    What is the difference between Jump Game and Jump Game II?

    Jump Game (LeetCode 55) asks whether the last index can be reached at all. Jump Game II (LeetCode 45) assumes it can and asks for the fewest jumps.


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Greedy Algorithm Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleJump Game | Leetcode 55 | Greedy Solution
    Next Article Minimum Platforms | Optimal Greedy Solution
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (2)
    Recent Posts

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.