Ctrl K

Longest Loop of Notes

Medium
There are n boxes numbered 0 to n - 1. Box i holds a note with the number next_box[i], the next box to open. All notes carry different numbers, so next_box is a permutation of 0 to n - 1. Open any box and keep following the notes. Sooner or later you come back to a box you have already opened. Return the largest number of distinct boxes you can open this way with a well-chosen starting box.
Example 1
next_box=[2, 0, 1, 4, 3] → 3

Starting from box 0 the trail goes 0 → 2 → 1 → 0, visiting three boxes. Boxes 3 and 4 point at each other, a loop of two.

Example 2
next_box=[0, 1, 2] → 1

Every box points to itself, so each loop is a single box.

Example 3
next_box=[1, 2, 3, 0] → 4
Constraints
  • 1 ≤ n ≤ 10⁵
  • 0 ≤ next_box[i] < n
  • All values of next_box are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWord Traced on a Letter Grid MediumDrain the Landlocked Ponds MediumLand Regions on a Map MediumRatio Chain Queries MediumRain Reaching Both Seas Medium
loading Python…
Input
next_box=[2, 0, 1, 4, 3]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 100 tests on the server, hidden ones included.