#55

Jump Game

Medium
ArrayDynamic ProgrammingGreedyGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a greedy strategy to track the furthest index we can reach at any point. If we can reach the last index or beyond, we return true.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable 'maxReach' to 0, which keeps track of the furthest index we can reach.
  2. 2Step 2: Iterate through the array, and for each index, check if it's reachable (i.e., index <= maxReach).
  3. 3Step 3: Update 'maxReach' to the maximum of its current value and the index plus the jump length at that index.
  4. 4Step 4: If at any point 'maxReach' is greater than or equal to the last index, return true.
  5. 5Step 5: If the loop ends and we haven't reached the last index, return false.
solution.py9 lines
1def canJump(nums):
2    maxReach = 0
3    for i in range(len(nums)):
4        if i > maxReach:
5            return False
6        maxReach = max(maxReach, i + nums[i])
7        if maxReach >= len(nums) - 1:
8            return True
9    return False

Complexity note: The time complexity is O(n) because we only traverse the array once, and the space complexity is O(1) since we use a constant amount of extra space.

  • 1The key observation is that if you can reach an index, you can potentially reach further indices based on the jump value at that index.
  • 2Greedy algorithms often yield optimal solutions for problems involving making a series of choices that lead to a final goal.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.