Problem Description
Given a binary string s and two integers minJump and maxJump, you start at index 0 (which is guaranteed to be '0'). From any index i, you can jump to any index j satisfying i + minJump ≤ j ≤ min(i + maxJump, s.length - 1) provided that s[j] is '0'. The goal is to determine whether you can reach the last index of the string.
Key Insights
- A straightforward BFS or DFS would be too slow for large inputs due to overlapping subproblems.
- Use dynamic programming with a sliding window (prefix sum) to efficiently track the cumulative reachability.
- Instead of checking each jump individually, maintain a sliding window sum over the dp values that denote whether previous positions are reachable.
- When the sliding window moves, add the new dp value entering the window and subtract the dp value leaving the window.
- The cell is marked reachable only if it is '0' and there exists at least one previous reachable index within the jump range.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string. Space Complexity: O(n) for the dp array.
Solution
The solution uses a dynamic programming approach combined with a sliding window technique. We create a boolean array dp where dp[i] indicates whether index i is reachable. We initialize dp[0] as true because we start from index 0. A variable (reachable) is used to maintain the count of reachable indices in the current window. For each index i, if i is within minJump distance from a previous index, we add dp[i - minJump] to reachable. If the index is beyond maxJump, we subtract dp[i - maxJump - 1] from reachable as its contribution is no longer valid. If the current character s[i] is '0' and reachable is greater than zero, we mark dp[i] as true. Finally, dp[s.length - 1] gives the answer.