SDE & MLE Prep

1871. Jump Game VII

Problem

s is a binary string starting with '0'. From index i you can jump to any j with i + minJump ≤ j ≤ i + maxJump and s[j] == '0'. Decide whether you can reach the last index from index 0.

Example: s = "011010", minJump = 2, maxJump = 3 → true

Constraints: length ≤ 10⁵.

i is reachable iff s[i] == '0' and some reachable index lies in [i − maxJump, i − minJump]. Keep a running count of reachable indices inside that window (add the index entering at i − minJump, drop the one leaving at i − maxJump − 1) — O(1) per position instead of scanning the window.

Complexity: O(n).

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