Find smallest start index avoiding left exit
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to analyze reachability and cycle behavior in array-based functional graphs, testing competency in array manipulation, traversal, loop detection, and runtime optimization within the Coding & Algorithms domain.
Constraints
- 0 <= n <= 200000
- -10^9 <= jump[i] <= 10^9
- An O(n) solution is expected.
Examples
Input: ([-1, -1, -1, -1, 2],)
Expected Output: 4
Explanation: Indices 0 through 3 eventually move to -1. Starting at 4 jumps to 6, which exits on the right, so the answer is 4.
Input: ([0, -2, 1],)
Expected Output: 0
Explanation: Index 0 jumps to itself forever, which is allowed. Therefore the smallest valid start is 0.
Input: ([-1, -1, -1],)
Expected Output: -1
Explanation: Every starting index eventually exits through the left boundary.
Input: ([1, 1, -1],)
Expected Output: 0
Explanation: Starting from 0 gives 0 -> 1 -> 2 -> 1, which loops inside the array and never exits left.
Input: ([],)
Expected Output: -1
Explanation: There is no valid starting index in an empty array.
Input: ([-1],)
Expected Output: -1
Explanation: The only starting index immediately exits to the left.
Input: ([0],)
Expected Output: 0
Explanation: The only index loops to itself, so it is valid.
Input: ([1, -2, 3, -4, 1],)
Expected Output: 2
Explanation: Starts 0 and 1 exit left, while 2 jumps to 5 and exits right. So the smallest valid start is 2.
Hints
- Think of each index as a node with exactly one outgoing edge to `i + jump[i]`.
- If a walk revisits a node already seen in the same exploration, you found an internal cycle, which is safe because it can never suddenly exit left.