Skip to the code
cf.
+50 XP

#449 Longest Redirect Loop

hard

A CDN config sends each page to at most one other page. Pages are numbered 0 to n - 1, and redirects[i] is the page that page i redirects to, or -1 if page i doesn't redirect.

Following redirects from some pages goes around in a loop forever. Write longestLoop(redirects) that returns the number of pages in the longest such loop, or -1 if there is no loop. A page that redirects to itself is a loop of 1.

Example 1

Input: redirects = [1,2,0,4,3,-1]
Output: 3

Pages 0 → 1 → 2 → 0 form a loop of 3. Pages 3 and 4 form a loop of 2.

Example 2

Input: redirects = [-1,0]
Output: -1

Page 1 goes to 0, and page 0 stops.

Constraints

  • 1 <= redirects.length <= 100000
  • -1 <= redirects[i] < redirects.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).