/**
* Problem: LeetCode 1871 - Jump Game VII
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean canReach(String s, int minJump, int maxJump) {
int n = s.length();
if (s.charAt(n - 1) == '1') {
return false;
}
boolean[] dp = new boolean[n];
dp[0] = true;
int reachableInWindow = 0;
for (int i = 1; i < n; i++) {
// Add (i - minJump) to sliding window
if (i >= minJump && dp[i - minJump]) {
reachableInWindow++;
}
// Remove (i - maxJump - 1) from sliding window
if (i > maxJump && dp[i - maxJump - 1]) {
reachableInWindow--;
}
// Current index is reachable if within valid jump range and character is '0'
if (s.charAt(i) == '0' && reachableInWindow > 0) {
dp[i] = true;
}
}
return dp[n - 1];
}
}
"""
Problem: LeetCode 1871 - Jump Game VII
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
n = len(s)
if s[n - 1] == '1':
return False
dp = [False] * n
dp[0] = True
reachable_in_window = 0
for i in range(1, n):
# Element entering the sliding window: i - minJump
if i >= minJump and dp[i - minJump]:
reachable_in_window += 1
# Element leaving the sliding window: i - maxJump - 1
if i > maxJump and dp[i - maxJump - 1]:
reachable_in_window -= 1
if s[i] == '0' and reachable_in_window > 0:
dp[i] = True
return dp[n - 1]
/**
* Problem: LeetCode 1871 - Jump Game VII
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool canReach(string s, int minJump, int maxJump) {
int n = s.length();
if (s[n - 1] == '1') {
return false;
}
vector<bool> dp(n, false);
dp[0] = true;
int reachableInWindow = 0;
for (int i = 1; i < n; ++i) {
if (i >= minJump && dp[i - minJump]) {
reachableInWindow++;
}
if (i > maxJump && dp[i - maxJump - 1]) {
reachableInWindow--;
}
if (s[i] == '0' && reachableInWindow > 0) {
dp[i] = true;
}
}
return dp[n - 1];
}
};
/**
* Problem: LeetCode 1871 - Jump Game VII
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} s
* @param {number} minJump
* @param {number} maxJump
* @return {boolean}
*/
var canReach = function(s, minJump, maxJump) {
const n = s.length;
if (s[n - 1] === '1') {
return false;
}
const dp = new Uint8Array(n);
dp[0] = 1;
let reachableInWindow = 0;
for (let i = 1; i < n; i++) {
if (i >= minJump && dp[i - minJump]) {
reachableInWindow++;
}
if (i > maxJump && dp[i - maxJump - 1]) {
reachableInWindow--;
}
if (s[i] === '0' && reachableInWindow > 0) {
dp[i] = 1;
}
}
return dp[n - 1] === 1;
};
TIME COMPLEXITY
O(N)
SPACE COMPLEXITY
O(N)
TOPICS
Dynamic Programming
Prefix Sum
Sliding Window
String