Jump Game VII — LeetCode 1871 Python Solution
MediumStringDynamic ProgrammingPrefix SumSliding Window
- Problem
- #1871
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 55Jump GameMediumLeetCode 1208Get Equal Substrings Within BudgetMediumLeetCode 1888Minimum Number of Flips to Make the Binary String AlternatingMediumLeetCode 2024Maximize the Confusion of an ExamMediumLeetCode 1044Longest Duplicate SubstringHardLeetCode 1234Replace the Substring for Balanced StringMedium
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.