LeetSolved

Find solutions to all LeetCode problems here.

45.

Jump Game II

Medium

Problem Description

Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps.

Examples

Input: [2,3,1,1,4]
Output: 2

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

Constraints

Approach to Solve

Use a greedy approach to find the minimum number of jumps.

Code Implementation

class Solution:
    def jump(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 1:
            return 0
        jumps = 0
        current_max = 0
        next_max = 0
        for i in range(n - 1):
            next_max = max(next_max, i + nums[i])
            if i == current_max:
                jumps += 1
                current_max = next_max
                if current_max >= n - 1:
                    break
        return jumps

Explanation

This solution uses a greedy approach to solve the problem. Here's a detailed explanation of the algorithm:

  1. Initialize variables: jumps (number of jumps), currentMax (farthest reachable index in the current jump), and nextMax (farthest reachable index in the next jump).
  2. Iterate through the array from left to right (except the last element):
    • Update nextMax to be the maximum of its current value and i + nums[i].
    • If we've reached the currentMax:
      • Increment jumps.
      • Update currentMax to nextMax.
      • If currentMax is greater than or equal to the last index, break the loop.
  3. Return the number of jumps.

The time complexity is O(n) as we iterate through the array once, and the space complexity is O(1) as we only use a constant amount of extra space.

Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1)
Code copied to clipboard!