Skip to the code
cf.
+25 XP

#236 Where the Redirect Loop Starts

medium

Redirect rules are stored in next: page i redirects to page next[i], or loads normally when next[i] === -1. This is a linked list in an array: next[i] is the index of the node after node i.

A visitor starts at page 0 and follows redirects. To fix a loop you need its entry point. Write loopEntry(next) that returns the index of the first page the visitor reaches that is part of the loop (the first page they would visit twice), or -1 if the visitor reaches a page that loads. Use O(1) extra space.

Example 1

Input: next = [1,2,3,1]
Output: 1

The walk is 0, 1, 2, 3, 1, ..., so page 1 is the first page visited twice.

Example 2

Input: next = [1,2,-1]
Output: -1

Page 2 loads, so there is no loop.

Constraints

  • 1 <= next.length <= 10^4
  • next[i] is -1 or a valid index 0 <= next[i] < next.length.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).