Array Nesting

You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].

You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ...} subjected to the following rule:

  • The first element in s[k] starts with the selection of the element nums[k] of index = k.
  • The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
  • We stop adding right before a duplicate element occurs in s[k].

Return the longest length of a set s[k].

Example 1
Inputnums = [5,4,0,3,1,6,2]
Output4
One of the longest sets is s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}, which has length 4.
Example 2
Inputnums = [0,1,2]
Output1
Each set stops immediately before repeating its starting value, so the longest length is 1.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] < nums.length
  • All the values of nums are unique.

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate