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

&nbsp;
Example 1:

Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation: 
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}


Example 2:

Input: nums = [0,1,2]
Output: 1


&nbsp;
Constraints:


	1 &lt;= nums.length &lt;= 105
	0 &lt;= nums[i] &lt; nums.length
	All the values of nums are unique.


class Solution:
    def arrayNesting(self, nums: List[int]) -> int:
        max_len = 0
        visited = set()
        def dfs(nums, index, dfs_visited):
            if index in dfs_visited:
                return len(dfs_visited)
            
            # add the index to dfs_visited and visited
            visited.add(index)
            dfs_visited.add(index)
            return dfs(nums, nums[index], dfs_visited)
            
        for i in range(len(nums)):
            if i not in visited:
                max_len = max(max_len, dfs(nums, i, set()))
        return max_len
class Solution {
    public int arrayNesting(int[] nums) {
        int res=0;
        boolean[] visited = new boolean[nums.length];
        for(int i=0;i<nums.length;i++){
            if(!visited[i]){
                int len = dfs(nums,i,visited);
                res = Math.max(res,len);
            }
        }
        return res;
    }
    public int dfs(int[] nums,int i,boolean[] visited){
        if(visited[i]) return 0;
        visited[i] = true;
        return 1+dfs(nums,nums[i],visited);
    }
}
class Solution {
public:
    int dfs(vector<int>&nums,int ind,int arr[],int res)
    {
        if(arr[ind]==1)
            return res;
        res++;
        arr[ind]=1;
        return dfs(nums,nums[ind],arr,res);
    }
    int arrayNesting(vector<int>& nums) {
        
        int arr[nums.size()],ans=0;
        for(int i=0;i<nums.size();i++)
            arr[i]=0;
        for(int i=0;i<nums.size();i++)
        {
            int res=dfs(nums,i,arr,0);
            ans=max(res,ans);
        }
        return ans;
    }
};
var arrayNesting = function(nums) {
	return nums.reduce((result, num, index) => {
		let count = 1;

		while (nums[index] !== index) {
			const next = nums[index];
			[nums[index], nums[next]] = [nums[next], nums[index]];
			count += 1;
		}
		return Math.max(result, count);
	}, 0);
};
Array Nesting