Taro Logo

Jump Game II

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+22
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
984 views
Topics:
ArraysDynamic ProgrammingGreedy Algorithms

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

  • 0 <= j <= nums[i] and
  • i + j < n

Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

Example 1:

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

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

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 1000
  • It's guaranteed that you can reach nums[n - 1].

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the last index is unreachable from the start?
  2. What is the maximum length of the array and the maximum value of the elements within it?
  3. Can the array be empty or contain only a single element, and if so, what should be the expected output?
  4. Are all elements in the input array guaranteed to be non-negative integers?
  5. If there are multiple ways to reach the last index with the minimum number of jumps, does the problem require returning a specific path, or is the minimum jump count alone sufficient?

Brute Force Solution

Approach

Imagine you are trying to cross a path of stepping stones where each stone tells you the maximum distance you are allowed to jump forward. The brute force approach involves trying every single possible combination of jumps to see which path gets you to the end using the fewest steps.

Here's how the algorithm would work step-by-step:

  1. Start at the very first stone at the beginning of the path.
  2. Look at how far you are allowed to jump from your current position, and imagine trying every single valid jump distance.
  3. For every stone you could possibly jump to next, treat that as a new starting point and repeat the process of trying all possible future jumps.
  4. Keep following every single possible branch of jump choices until you either fall short before reaching the end or successfully make it to the final stone.
  5. Count the total number of jumps you took for every successful path that made it to the end.
  6. Compare the jump counts from all the successful paths you discovered.
  7. Pick the smallest number of jumps out of all the options, which represents the absolute fewest steps needed to reach the end.

Code Implementation

def jump_game_brute_force(array_of_numbers):
    def explore_paths(current_position, jump_count):
        # Stop exploring this branch if we have already reached or passed the final destination
        if current_position >= len(array_of_numbers) - 1:
            return jump_count

        max_reach = array_of_numbers[current_position]
        if max_reach == 0:
            return float('inf')

        minimum_jumps = float('inf')

        # Try every single possible jump distance from the current stone to explore all paths
        for next_step in range(1, max_reach + 1):
            result = explore_paths(current_position + next_step, jump_count + 1)
            if result < minimum_jumps:
                minimum_jumps = result

        return minimum_jumps

    # Guard against empty arrays or trivial paths where no movement is required
    if len(array_of_numbers) <= 1:
        return 0

    total_minimum_jumps = explore_paths(0, 0)

    # Ensure we return zero instead of infinity if the target is completely unreachable
    if total_minimum_jumps == float('inf'):
        return 0

    return total_minimum_jumps

Big(O) Analysis

Time Complexity
O(2^n) – Starting from the first stone, the algorithm branches out by trying every possible jump distance to reach subsequent stones. Each of those destination stones then branches out again into its own set of possible future jumps, repeating the process recursively for every valid path until reaching the end. In the worst-case scenario where many jumps are possible from each stone, this recursive exploration creates a branching factor that grows exponentially with the size of the array n. Summing up all these branching paths results in roughly 2 to the power of n operations, which simplifies to an exponential time complexity of O(2^n).
Space Complexity
O(1) – The brute force approach described relies entirely on tracking a few primitive variables like the current position, jump counts, and loop indices rather than creating any dynamic data structures. Furthermore, because the path is explored through iterative branching or recursive exploration without storing intermediate paths in memory, the recursion stack or temporary storage does not scale with the input size N. Therefore, the extra memory required remains constant regardless of how many stepping stones are on the path.

Optimal Solution

Approach

Instead of testing every possible sequence of jumps, the optimal strategy treats the journey like a series of checkpoints organized by distance. By looking at how far you can reach from your current stopping points, you plan your next mandatory stop only when you absolutely have to.

Here's how the algorithm would work step-by-step:

  1. Imagine you are on a road trip where every stop gives you a maximum driving range.
  2. Stand at your starting location and look at all the future stops you can reach within your current tank of gas.
  3. Do not choose your next stopping point immediately; instead, look at all the places you can reach from those upcoming spots to see which one gets you the absolute farthest down the road.
  4. Count taking a step forward whenever you finally reach the end of your current driving range and must officially refuel at your previously chosen furthest spot.
  5. Repeat this process of looking ahead to find the absolute maximum reach from your current cluster of options.
  6. Keep track of these boundaries so you always know when your current range is exhausted and a new step must be counted.
  7. Continue this strategy until your furthest possible reach easily covers or passes the final destination.

Code Implementation

def jump(array_of_nums):    if len(array_of_nums) <= 1:        return 0    jump_count = 0    current_furthest_reach = 0    next_furthest_reach = 0    # We evaluate all reachable indices within our current range before committing to a jump.    for current_index in range(len(array_of_nums) - 1):        next_furthest_reach = max(next_furthest_reach, current_index + array_of_nums[current_index])        # A jump is forced only when we exhaust the boundary of our current driving range.        if current_index == current_furthest_reach:            jump_count += 1            current_furthest_reach = next_furthest_reach            # We terminate early if our current reach already covers or passes the final destination.            if current_furthest_reach >= len(array_of_nums) - 1:                break    return jump_count

Big(O) Analysis

Time Complexity
O(n) – As we traverse the array of size n to evaluate each reachable stopping point and calculate the furthest possible reach, a single pass visits each element at most once. We maintain boundaries for our current range and update our maximum reach without rescanning previously visited elements. This linear progression means the number of operations grows in direct proportion to the size of the input, simplifying to O(n).
Space Complexity
O(1) – The algorithm relies entirely on a few primitive scalar variables to track the current furthest reach, the end of the current jump boundary, and the jump counter. These variables occupy a constant amount of memory regardless of the input size N. No auxiliary data structures, temporary lists, or recursion stack frames are utilized during execution. Therefore, the extra memory required remains strictly constant as the input array grows.

Edge Cases

Array with a single element
How to Handle:
Return zero jumps immediately because we are already standing at the final destination.
Array starting with a zero where the second element is non-zero
How to Handle:
Start at index zero, take one jump using the first element's capacity, and continue the greedy range expansion.
Array where the first element can jump directly to the last index
How to Handle:
The greedy algorithm will evaluate the max reach, see it covers the last index, and return exactly one jump.
Array containing consecutive zeros blocking progress
How to Handle:
Although the problem statement guarantees the last index is reachable, the greedy tracker naturally maintains the furthest possible reach before dead ends.
Extremely large arrays up to the maximum constraints
How to Handle:
The linear time greedy approach processes the array in a single pass without recursion overhead, preventing stack overflows and ensuring optimal scalability.
Array with all elements equal to one
How to Handle:
The algorithm increments the jump counter at every single step, correctly returning a total of n minus one jumps for an array of size n.
Array with decreasing or strictly increasing jump values
How to Handle:
The greedy window dynamically updates the farthest reachable index at each step regardless of the local value distribution.
Input values near the maximum integer limit
How to Handle:
The jump reach calculations are bounded within the array length constraints, avoiding any potential integer overflow issues.
0/75 completed