Treat each index as a node of a graph with up to two edges: jump arr[i] steps right, or arr[i] steps left, wrapping around the ends. The question is then "can you reach a node whose value is 0 from the start": a graph search. Recursively: if the value here is 0 return true; if this index was already visited return false (that's what stops infinite loops); otherwise mark it and try both jumps. Wrapping is modular arithmetic: (i + v) % n to the right and ((i - v) % n + n) % n to the left, because % can return a negative number in JavaScript. Each index is visited once, so it's O(n) time and space. For the follow-up, replace the call stack with a queue: push the start, and repeatedly take an index, test it, and push its unvisited neighbours.
Given an array of integers like [1,2,0,4,3] and a starting index, return true if you can reach a 0 value. Each value is how many steps left/right you can move (you must take exactly that many). Wrap around from end to start when you run out of room. Solve recursively with visited-index tracking, then convert to an iterative queue-based solution as a follow-up.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Three base cases in order: a zero here means success; an index seen before means this route is going in a circle; otherwise mark it and recurse into both neighbours. The visited set is shared by every call, so each index is expanded once and the search is O(n). The left jump adds n before the final % because -1 % 5 is -1 in JavaScript, not 4. The last check shows the limit of recursion: a chain of 200,000 jumps overflows the call stack.
// From index i you must move exactly arr[i] steps, left or right, wrapping around the ends.// Depth-first search; `visited` stops the walk from going round in circles.function canReachZero(arr, start, visited = new Set()) {if (arr[start] === 0) return true;if (visited.has(start)) return false;visited.add(start);const n = arr.length;const right = (start + arr[start]) % n;const left = (((start - arr[start]) % n) + n) % n; // % can give a negative result in JavaScriptreturn canReachZero(arr, right, visited) || canReachZero(arr, left, visited);}
passes 7 checks run on every build, against the native method where there is one
- the example array, from every start
- starting on a zero is already there
- wrapping past the end and before the start
- a cycle that never meets the zero ends with false
- a jump of the array's length, or a multiple, lands where it started
- the array is not changed
- the weakness: a long chain of jumps overflows the call stack
The queue holds indexes still to examine. An index is marked visited when it is added, not when it is taken out, so it can't be queued twice. Reading with a moving head instead of shift() keeps each step O(1). It answers the same question in the same O(n), with no recursion depth to worry about. A start index outside the array finds nothing and returns false.
// The follow-up: the same search with a queue instead of the call stack (breadth-first).// No recursion, so a long chain of jumps can't overflow the stack.function canReachZero(arr, start) {const n = arr.length;const visited = new Set([start]);const queue = [start];for (let head = 0; head < queue.length; head++) {const i = queue[head];if (arr[i] === 0) return true;for (const next of [(i + arr[i]) % n, (((i - arr[i]) % n) + n) % n]) {if (!visited.has(next)) {visited.add(next);queue.push(next);}}}return false;}
passes 8 checks run on every build, against the native method where there is one
- the example array, from every start
- starting on a zero is already there
- wrapping past the end and before the start
- a cycle that never meets the zero ends with false
- a jump of the array's length, or a multiple, lands where it started
- the array is not changed
- a long chain of jumps is fine
- a start outside the array is false, not an exception
A queue explores in order of distance from the start, so the first zero found is one of the nearest. Storing, for each index, the index it was reached from lets you walk backwards from the zero to the start and return the route. fewestJumps is that route's length minus one. Depth-first search would also find a route, but not necessarily a shortest one.
// Breadth-first search visits indexes in order of distance, so the first zero it meets is a// nearest one. Remembering where each index was reached from gives the route itself.function pathToZero(arr, start) {const n = arr.length;const from = new Map([[start, null]]); // index -> the index we jumped fromconst queue = [start];for (let head = 0; head < queue.length; head++) {const i = queue[head];if (arr[i] === 0) {const path = [];for (let at = i; at !== null; at = from.get(at)) path.unshift(at);return path;}for (const next of [(i + arr[i]) % n, (((i - arr[i]) % n) + n) % n]) {if (!from.has(next)) {from.set(next, i);queue.push(next);}}}return null;}const canReachZero = (arr, start) => pathToZero(arr, start) !== null;const fewestJumps = (arr, start) => (pathToZero(arr, start)?.length ?? 0) - 1; // -1: unreachable
passes 11 checks run on every build, against the native method where there is one
- the example array, from every start
- starting on a zero is already there
- wrapping past the end and before the start
- a cycle that never meets the zero ends with false
- a jump of the array's length, or a multiple, lands where it started
- the array is not changed
- a long chain of jumps is fine
- a start outside the array is false, not an exception
- pathToZero returns the indexes visited, start to zero
- every step of a path is a legal jump
- the path is a shortest one
Reachability in any graph
"Can I get from here to there" is the same search whether the nodes are array indexes, pages, or screens in a navigation flow. The visited set is what makes it finish.
Carousels and ring buffers
Wrapping an index around the ends is everyday code: next and previous in a carousel, or a circular buffer. The left wrap needs the + n because of how % treats negatives.
Recursion depth
Engines limit the call stack, and a recursive search over a long path throws a RangeError. An explicit queue or stack lives on the heap and has no such limit.
No visited set: two indexes that jump to each other recurse forever.
(i - v) % nfor the left jump, which is negative whenv > i.Marking an index visited only when it is processed, so it is queued several times.
queue.shift()in the loop, which makes the search O(n²) on a long array.Returning as soon as one direction fails instead of trying the other.
Forgetting that a jump of exactly
nsteps lands on the same index.
What's the time and space complexity?
O(n) time: each index is visited once and has two edges. O(n) space for the visited set, plus the recursion stack or the queue, each at most n.
Depth-first or breadth-first: does it matter?
For a yes or no answer, no. Breadth-first finds a shortest route and never recurses; depth-first is shorter to write. An iterative depth-first search is the same code with pop() instead of a moving head.
What if you may not use extra memory?
Mark visited indexes in the array itself, for example by negating the value (keeping the absolute value for the jump), and restore it afterwards if the caller needs the array unchanged.
What if values can be negative?
Decide what it means. If a negative value is simply a jump in the other direction, the two neighbours are unchanged, since you already try both directions; the modular arithmetic handles it.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion
- en.wikipedia.org/wiki/Breadth-first_search
- en.wikipedia.org/wiki/Depth-first_search