Taro Logo

Jump Game

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+23
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
Profile picture
1.3K views
Topics:
ArraysGreedy Algorithms

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.

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.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 105

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 is the maximum length of the `nums` array and the maximum possible value of an element within it?
  2. Can the array contain negative integers, or are all values guaranteed to be non-negative?
  3. How should we handle an array with only a single element?
  4. If the first element is `0` and the array has a length greater than one, should the function immediately return false?
  5. Are there any memory constraints or expectations regarding modifying the input array in place?

Brute Force Solution

Approach

Imagine you are standing at the starting point of a path made of stepping stones, and each stone allows you to take a certain number of forward steps. The brute force approach involves trying every single possible sequence of jumps to see if any of them can successfully lead you all the way to the final stone.

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

  1. Begin your journey at the very first stepping stone.
  2. Look at the number written on your current stone, which tells you the maximum number of steps you can legally make forward.
  3. Choose one of the allowed forward steps and move to that new stone.
  4. From this new stone, repeat the process by choosing another valid forward step.
  5. Continue making choices and moving forward until you either get stuck on a stone with nowhere to go or successfully reach the final destination stone.
  6. If you get stuck, back up to your previous decision point and try a different forward step size.
  7. Exhaustively repeat this trial-and-error process across every single branching path of choices until you find a path that works or prove that every possible combination leads to a dead end.

Code Implementation

def can_jump(stepping_stones):
    target_destination = len(stepping_stones) - 1

    def explore_paths(current_position):
        if current_position >= target_destination:
            return True

        maximum_steps = stepping_stones[current_position]
        if maximum_steps == 0:
            return False

        # We branch out into every possible jump size to exhaustively check all pathways
        for step_size in range(1, maximum_steps + 1):
            next_position = current_position + step_size
            if explore_paths(next_position):
                return True

        # If all branch attempts fail, this path is a dead end and we must backtrack
        return False

    # We initiate the recursive exploration starting from the very first stepping stone
    return explore_paths(0)

Big(O) Analysis

Time Complexity
O(2^n) – Because the brute force approach uses trial and error to exhaustively explore every possible branching sequence of jumps from each stepping stone, the number of choices multiplies at each step. For an array of size n, this recursive exploration leads to a binary-like or multi-branching tree of possibilities where each stone visited doubles or expands the decision paths. The total operations approximate an exponential tree growth of 2 raised to the power of n, which simplifies to O(2^n).
Space Complexity
O(1) – The brute force trial-and-error approach described in the explanation relies entirely on a recursive backtracking strategy. Since we only maintain a few scalar variables to track our current position and decision choices without utilizing auxiliary arrays or hash maps, the extra memory usage remains constant. The recursion stack frames can grow up to a maximum depth proportional to N in the worst-case scenario where we explore paths sequentially. However, because we only remember our current path rather than gathering items into a pile or storing intermediate results globally, the peak auxiliary memory footprint does not scale with the input size N.

Optimal Solution

Approach

Instead of trying to map out every single path forward, the optimal strategy works backwards or keeps track of the furthest possible reach from the very beginning. By constantly updating how far you can travel based on your current standing, you can instantly tell if the final destination is within your maximum possible range.

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

  1. Start at your initial stepping stone and look at how far forward your current leap can potentially carry you.
  2. As you move from stone to stone, continuously update your vision to see what the absolute furthest point is that you can eventually reach.
  3. If at any point your furthest possible reach falls short of the stone you are currently standing on, it means you are completely stuck and cannot move any further.
  4. If you successfully manage to advance and your furthest possible reach extends all the way to or beyond the final destination, you have your answer.
  5. Stop and conclude that reaching the end is entirely possible without ever needing to test every single sequence of jumps.

Code Implementation

def can_jump(jump_lengths):    maximum_reachable_index = 0    for current_index, jump_length in enumerate(jump_lengths):        # If we cannot reach the current stone, we are permanently stuck and cannot proceed further.        if current_index > maximum_reachable_index:            return False        # Continuously update the furthest possible index we can ever reach from our current standing.        potential_reach = current_index + jump_length        if potential_reach > maximum_reachable_index:            maximum_reachable_index = potential_reach        # If our furthest reach extends to or beyond the final destination, we have won.        if maximum_reachable_index >= len(jump_lengths) - 1:            return True    return maximum_reachable_index >= len(jump_lengths) - 1

Big(O) Analysis

Time Complexity
O(n) – The cost is driven by a single pass through the array of size n as we iterate from the first stepping stone to the last. During this traversal, we perform constant-time operations at each step, such as updating our maximum reachable index and comparing our current position against that limit. Because we visit each of the n elements at most once without any nested loops or redundant path exploration, the total operations scale linearly. This brings us to approximately n operations in the worst-case scenario, which simplifies cleanly to O(n).
Space Complexity
O(1) – The algorithm maintains a single variable to track the furthest possible reach as it iterates through the input array. No auxiliary data structures, temporary lists, or recursive call stacks are utilized regardless of the input size N. Consequently, the extra memory consumption remains entirely constant as N scales. This matches the plain English approach of just keeping track of your maximum possible range on the fly without storing past states.

Edge Cases

Single-element array
How to Handle:
The greedy tracker initializes at index 0 and immediately reaches the final index, returning true.
Array starting with a zero
How to Handle:
The maximum reach remains 0 at index 0, preventing any forward movement and returning false.
Array with zeros blocking the path
How to Handle:
The greedy algorithm checks if the current index exceeds the maximum reachable distance, returning false when trapped.
Extremely large jump values at the beginning
How to Handle:
The maximum reach extends beyond the final index, ensuring the loop condition satisfies early and returns true.
Strictly decreasing jumps of one
How to Handle:
The reach increments by exactly one at each step, allowing the traversal to barely reach the final index.
Maximum-sized inputs up to constraint limits
How to Handle:
A single linear scan runs in O(n) time and O(1) space, easily scaling without exceeding memory or time limits.
Array elements with large integer values
How to Handle:
Reach calculations are capped at the array length to prevent unnecessary iterations or integer overflow issues.
0/75 completed