Earliest Safe Starting Cell in a Jump Array
Trees & GraphsAuto-graded · 25 test casesLast updated
Find the smallest start index in a jump array whose walk never goes below index 0, handling cycles and right exits, ideally in linear time.
You are given an integer list steps with n entries, indexed from 0. Standing on cell i, you must jump to cell i + steps[i]. A positive value moves you to the right, a negative value moves you to the left, and zero keeps you where you are.
Pick a starting cell s and keep jumping according to this rule. The walk can end or continue in one of these ways:
- If you land on a cell with index below
0, you have fallen off the left edge. - If you land on a cell with index
nor greater, you have left through the right edge, and the walk stops there. This is harmless. - The walk may also bounce around inside the list forever, which is also harmless.
A start s is safe if the walk beginning at s never lands on a negative index.
Return the smallest safe starting index. If no starting index is safe, return -1. An empty list has no safe start, so return -1.
A solution that runs in linear time is expected, so simulating every start independently from scratch is not the goal.
Constraints
0 <= n <= 10^5(the list may be empty)- Each
steps[i]is an integer that may be negative, zero, or positive, and may be large in magnitude - There is no wraparound: any position outside
[0, n)ends the walk - The function returns a single integer: the smallest safe index, or
-1
Examples
Example 1
Input: earliest_safe_start([2, -1, 2, -1])
Output: 0
Example 2
Input: earliest_safe_start([-1, -1])
Output: -1
Example 3
Input: earliest_safe_start([1, 1, 1])
Output: 0
Hints
Hint 1
Every cell has exactly one next cell, so the future of a walk depends only on the cell you are standing on. Two starts that reach the same cell share the same outcome from there on.
Hint 2
Record a result per cell: unknown, falls off left, or safe. When a walk reaches a cell with a known result, copy that result to every cell visited on the current walk instead of continuing.
Hint 3
Use a separate 'on the current walk' marker. Hitting such a cell means you closed a new cycle, which is safe, while hitting a cell resolved earlier means you inherit its stored result. Use an explicit list for the path rather than recursion.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each cell has exactly one outgoing move, i -> i + steps[i], so the board is a functional graph. A walk from any start ends in exactly one of three ways: it falls off the left (unsafe), it exits on the right (safe), or it enters a cycle inside the list (safe).
Because the next cell depends only on the current cell, every cell on a walk shares the outcome of the walk's end. So we resolve each cell once and reuse the answer.
We keep a state per cell:
| State | Meaning |
|---|---|
| 0 | unknown |
| 1 | falls off the left edge |
| 2 | safe |
| 3 | on the walk currently being explored |
For every unresolved start:
- Walk forward, marking each new cell as
3and appending it topath. - Stop when the position leaves
[0, n)or reaches a cell whose state is not0. - Decide the result:
- position
< 0: result1. - position
>= n: result2. - position is a cell with state
3: we closed a cycle on this walk, so result2. - otherwise the cell was resolved earlier, so inherit its state.
- position
- Assign the result to every cell in
path.
Finally, scan left to right and return the first cell with state 2, or -1 if none exists.
Why it is correct
- Determinism means copying the endpoint's outcome back along the path is exact.
- State
3only appears on the current walk, so meeting it means a genuine new cycle, which never leaves the array and is therefore safe. Cells leading into the cycle share that fate. - Meeting an earlier-resolved cell must inherit its stored state, which can be either
1or2; this is why the in-progress marker is kept distinct. - Every cell ends as
1or2, so the left-to-right scan gives the minimum safe start.
Complexity
- Time: O(n). Each cell is added to a path once and finalized once; every step either visits a fresh cell or ends the walk.
- Space: O(n) for the state array and path buffer.
Reference solution
from typing import List
def earliest_safe_start(steps: List[int]) -> int:
n = len(steps)
# 0 = unknown, 1 = falls off left, 2 = safe, 3 = on current walk
state = [0] * n
for start in range(n):
if state[start] != 0:
continue
path = []
pos = start
while 0 <= pos < n and state[pos] == 0:
state[pos] = 3
path.append(pos)
pos += steps[pos]
if pos < 0:
result = 1
elif pos >= n:
result = 2
elif state[pos] == 3:
result = 2
else:
result = state[pos]
for idx in path:
state[idx] = result
for idx, val in enumerate(state):
if val == 2:
return idx
return -1