Jump Game VII Problem
#1871
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1871.
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'. You can move from index i to index j if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1), ands[j] == '0'.
Return true if you can reach index s.length - 1 in s, or false otherwise.
Example 1:
Input: s = "011010", minJump = 2, maxJump = 3
Output: true
Explanation:
In the first step, move from index 0 to index 3.
In the second step, move from index 3 to index 5.
Example 2:
Input: s = "01101110", minJump = 2, maxJump = 3
Output: false
Constraints:
2 <= s.length <= 10^5s[i]is either'0'or'1'.s[0] == '0'1 <= minJump <= maxJump < s.length
Solution
Approach: Dynamic Programming With Prefix Sums
Let f[i] say whether index i is reachable, with f[0] = true, and keep pre, where pre[i] is the number of reachable indices among the first i.
Index i is reachable when s[i] = '0' and some reachable j lies in [i - maxJump, i - minJump]. Whether such a j exists is a range count on pre, which takes O(1). The answer is f[n - 1].
Complexity: O(n) time and O(n) space.
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]