Jump Game II — LeetCode 45 Python Solution

MediumGreedyArrayDynamic Programming
Problem
#45
Pattern
Greedy
Reading time
2 min

The problem

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

Example

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.

Python solution

Python
class Solution:
    def jump(self, nums: List[int]) -> int:
        ans = mx = last = 0
        for i, x in enumerate(nums[:-1]):
            mx = max(mx, i + x)
            if last == i:
                ans += 1
                last = mx
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 45. Jump Game II is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 45. Jump Game II?
LeetCode 45. Jump Game II is rated Medium on LeetCode.
What is the time complexity of LeetCode 45. Jump Game II?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 45. Jump Game II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 45. Jump Game II cover?
LeetCode 45. Jump Game II is tagged Greedy, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview