Skip to the code
cf.
+10 XP

#235 Detect a Redirect Loop

easy

A site's redirect rules are stored in an array next. Page i redirects to page next[i], and next[i] === -1 means page i loads normally. Each page has at most one redirect, so following the rules from a page is like walking a linked list where next[i] is the index of the node after node i.

A visitor opens page 0 and follows redirects. Write hasRedirectLoop(next) that returns true if the visitor would be redirected forever (the walk reaches a page it already visited), or false if it reaches a page that loads. Pages the visitor never reaches don't matter. Try to use O(1) extra space.

Example 1

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

Page 0 goes to 1, 2, 3, then back to 1, forever.

Example 2

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

Pages 0, 1, 2, and page 2 loads.

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).