AlgoInsight

DSA problem

Jump Game VII

MediumGreedyPattern: Greedytop600AmazonGoogleMicrosoftBloombergApple

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) and s[j] == '0'. Return true if you can reach index s.length - 1 in s, or false otherwise.

The naive recursive solution explores every reachable index by trying all jumps in [i + minJump, i + maxJump] from each position. This balloons to exponential time because the same index gets visited from many predecessors. Memoizing the recursion brings it down to O(n * (maxJump - minJump)), but for n up to 10^5 even that quadratic-ish blowup is too slow.

The optimal approach reframes the problem as a BFS over reachable zero-positions but observes that the set of indices reachable in one hop from i is the contiguous window [i + minJump, i + maxJump]. As we sweep i left to right, the window slides forward monotonically. So instead of re-scanning the window, we keep a moving "earliest-not-yet-considered" pointer and only mark fresh zero indices inside the window as reachable.

Concretely, walk i from 0 to n - 1; only process i if it is itself reachable. For each reachable i, expand reachability to every j in [max(i + minJump, lastSeen + 1), i + maxJump] whose s[j] == '0'. Track lastSeen so each index is touched at most once across the whole run, giving a clean O(n) time, O(n) space solution. The boolean reach[n - 1] is the answer.

Examples

Example 1
Input: s = "011010", minJump = 2, maxJump = 3
Output: true
Explanation: From index 0 jump to index 3 (s[3] = '0'). From index 3 jump to index 5 (s[5] = '0'), which is the last index. Both jumps satisfy 2 <= jump <= 3, so the destination is reachable.
Example 2
Input: s = "01101110", minJump = 2, maxJump = 3
Output: false
Explanation: The only reachable zero from index 0 is index 2, but then every position in [4, 5] is a '1' and index 6 is also a '1'. No legal sequence of jumps lands on the final zero at index 7.
Example 3
Input: s = "00", minJump = 1, maxJump = 1
Output: true
Explanation: A single jump of size 1 from index 0 lands on index 1, which is the last index and is a '0'.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedystringsliding-windowbfsdynamic-programming

Browse all DSA problems