Skip to content
Problem 1871 · LeetCode 1871(opens in a new tab)

Jump Game VII

MediumDynamic programming

You are given a string s of 0s and 1s and two numbers, minJump and maxJump. You start on index 0, which is always 0. From index i you may jump to any index j with i + minJump ≤ j ≤ i + maxJump, as long as j is inside the string and s[j] is 0.

Return true if some sequence of jumps lands you on the last index, and false otherwise.

Example 1

Input:  s = "0100100", minJump = 2, maxJump = 3
Output: true
Why:    0 → 3 → 6, landing on 0s each time
2 more examples and the constraints

Example 2

Input:  s = "0011100", minJump = 1, maxJump = 2
Output: false
Why:    three 1s in a row are too wide to jump

Example 3

Input:  s = "00", minJump = 1, maxJump = 1
Output: true
Why:    one jump of length 1

Constraints

  • 2 ≤ length of s ≤ 100,000
  • Each s[i] is 0 or 1, and s[0] is 0
  • 1 ≤ minJump ≤ maxJump < length of s

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Mark every jumpO(n·k)
  2. Sliding window countO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeWork for 100,000 cells, wide rangeVerdict
Mark every jumpO(n·k)
Too slow for wide ranges
Sliding window countO(n)
Best; one pass

n = length of s, k = maxJump − minJump + 1.

Edge cases to test

  • Last cell is a 1. "01" is false at once: you can never land on a 1.
  • A wide wall of 1s. "0011100" with jumps of 1 to 2: no jump clears three 1s.
  • Fixed jump length. minJump = maxJump = 3 on "000000000": you land on 0, 3, 6 and overshoot the last index, 8.
  • One giant jump. "01111110" with maxJump = 7 jumps straight from 0 to the end.

Common mistakes

  • Updating count when the window is not yet full: cell i − minJump only exists when i ≥ minJump.
  • Removing the wrong cell from the window. The one leaving is i − maxJump − 1, not i − maxJump.
  • Setting reach[i] from the window alone and forgetting that s[i] must be 0.

How to talk through it

  1. 1Clarify. Do jumps only go forward? Must the landing cell be 0? Is index 0 always 0?
  2. 2Give the simple DP. From each reachable cell mark its range; say it is O(n·k) and too slow when the range is wide.
  3. 3Flip the direction. Ask which earlier cells could reach i. They form a window that slides by one.
  4. 4Count, do not scan. Keep the number of reachable cells in the window; one enters and one leaves per step.
  5. 5Test out loud. Run "01", "0011100" with 1 to 2, and a fixed jump that overshoots the end.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?