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 trueif you can reach indexs.length - 1ins, orfalseotherwise.
Input: s ="011010", minJump =2, maxJump =3Output: trueExplanation:
In the first step, move from index 0 to index 3.In the second step, move from index 3 to index 5.
First, consider the standard BFS approach: use a queue to explore all indices reachable from the current position within the [curr_idx + minJump, curr_idx + maxJump] range, returning true if the end is reached.
However, since some indices may be revisited, it’s efficient to use a visited array or set to track which positions have already been processed and skip them in future traversals.
However this approach will result in TLE. Even with a set, previously processed indices may still be checked inside the inner loop, leading to a worst-case time complexity of O(n^2).
To prevent this, we can track the farthest index processed so far and always begin the next search from that point, updating this maximum index as we go.
The main idea is to use BFS to explore reachable indices, but to avoid redundant work, we track the farthest index we’ve already processed. This prevents revisiting indices and ensures each index is processed only once, making the solution efficient.
classSolution {
public:bool canReach(string s, int minJump, int maxJump) {
int n = s.size();
if (s[n -1] !='0') return false;
queue<int> q;
q.push(0);
int maxReach =1;
while (!q.empty()) {
int i = q.front(); q.pop();
for (int j = max(i + minJump, maxReach); j <= min(i + maxJump, n -1); ++j) {
if (s[j] =='0') {
if (j == n -1) return true;
q.push(j);
}
}
maxReach = max(maxReach, i + maxJump +1);
}
return n ==1;
}
};
classSolution {
publicbooleancanReach(String s, int minJump, int maxJump) {
if(s.charAt(s.length() - 1) !='0')
returnfalse;
Queue<Integer> queue =new LinkedList<>();
queue.add(0);
// This variable tells us till which index we have processedint maxReach = 0;
while(!queue.isEmpty()){
int idx = queue.remove();
// If we reached the last indexif(idx == s.length() - 1)
returntrue;
// start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)]for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){
if(s.charAt(j) =='0')
queue.add(j);
}
// since we have processed till idx + maxJump so update maxReach to next index maxReach = Math.min(idx + maxJump + 1, s.length() - 1);
}
returnfalse;
}
}