KatInterview

Earliest Safe Starting Cell in a Jump Array

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphsfunctional-graphcycle-detectionmemoization

Last 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 n or 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.