Jump Game VII — LeetCode 1871 Python Solution

MediumStringDynamic ProgrammingPrefix SumSliding Window
Problem
#1871
Reading time
2 min

The problem

You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'.

Example

Input
s = "011010", minJump = 2, maxJump = 3
Output
true
Explanation
In the first step, move from index 0 to index 3.

Python solution

Python
class Solution:
    def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
        n = len(s)
        pre = [0] * (n + 1)
        pre[1] = 1
        f = [True] + [False] * (n - 1)
        for i in range(1, n):
            if s[i] == "0":
                l, r = max(0, i - maxJump), i - minJump
                f[i] = l <= r and pre[r + 1] - pre[l] > 0
            pre[i + 1] = pre[i] + f[i]
        return f[-1]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1871. Jump Game VII is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1871. Jump Game VII?
LeetCode 1871. Jump Game VII is rated Medium on LeetCode.
What is the time complexity of LeetCode 1871. Jump Game VII?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1871. Jump Game VII?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1871. Jump Game VII cover?
LeetCode 1871. Jump Game VII is tagged String, Dynamic Programming, Prefix Sum and Sliding Window 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