# Longest subset of nested elements from a given array

• Last Updated : 03 May, 2021

Given an array arr[] consisting of a permutation of numbers in the range [0, N – 1], the task is to find the length of the longest subset from the array such that the elements in the subset are of the form {arr[i], arr[arr[i]], arr[arr[arr[i]]], …}

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {5, 4, 0, 3, 1, 6, 2}
Output:
Explanation:
arr[arr[0]] is equal to arr[5]
arr[arr[arr[0]]] is equal to arr[6]
arr[arr[arr[arr[0]]]] is equal to arr[2]
One of the possible subsets from the array are {arr[0], arr[5], arr[6], arr[2]} = {5, 6, 2, 0}, which is the longest subset satisfying the given condition. Therefore, the required output is 4.

Input: arr[] ={3, 1, 4, 0, 2}
Output:
Explanation:
arr[arr[0]] is equal to arr[3]
One of the possible subset from the array is {arr[0], arr[3]} = {3, 0}
Therefore, the required output is 2.

Approach: Follow the steps below to solve the problem:

• Initialize a variable res = 0 to store the length of the longest subset of the array that satisfying the condition.
• Traverse the array arr[] and perform the following operations:
• Check if arr[i] is equal to i or not. If found to be true, then update res = max(res, 1).
• Initialize a variable, say index = i, to store the index of elements of a subset from the given array.
• Iterate over elements of a subset while arr[index] != index, update the current element of the subset to the current index and also update index = arr[index].
• Finally, update the res to the maximum of res and the count of elements in the current subset.
• Finally, print the res.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to find length of longest subset``// such that subset { arr[i], arr[arr[i]], .. }``int` `arrayNesting(vector<``int``> arr)``{` `  ``// Stores length of the longest subset``  ``// that satisfy the condition``  ``int` `res = 0;` `  ``// Traverse in the array, arr[]``  ``for` `(``int` `i = 0; i < arr.size(); i++)``  ``{` `    ``// If arr[i] equals to i``    ``if` `(arr[i] == i)``    ``{` `      ``// Update res``      ``res = max(res, 1);``    ``}``    ``else``    ``{` `      ``// Count of elements in a subset``      ``int` `count = 0;` `      ``// Stores index of elements in``      ``// the current subset``      ``int` `curr_index = i;` `      ``// Calculate length of a subset that``      ``// satisfy the condition``      ``while` `(arr[curr_index] != curr_index)``      ``{``        ``int` `next_index = arr[curr_index];` `        ``// Make visited the current index``        ``arr[curr_index] = curr_index;` `        ``// Update curr_index``        ``curr_index = next_index;` `        ``// Update count``        ``count++;``      ``}` `      ``// Update res``      ``res = max(res, count);``    ``}``  ``}``  ``return` `res;``}` `// Driver Code``int` `main()``{``  ``vector<``int``> arr = { 5, 4, 0, 3, 1, 6, 2 };``  ``int` `res = arrayNesting(arr);``  ``cout<

## Java

 `// Java program to implement``// the above approach` `import` `java.io.*;``import` `java.util.*;` `class` `sol {` `    ``// Function to find length of longest subset``    ``// such that subset { arr[i], arr[arr[i]], .. }``    ``public` `int` `arrayNesting(``int``[] arr)``    ``{` `        ``// Stores length of the longest subset``        ``// that satisfy the condition``        ``int` `res = ``0``;` `        ``// Traverse in the array, arr[]``        ``for` `(``int` `i = ``0``; i < arr.length; i++) {` `            ``// If arr[i] equals to i``            ``if` `(arr[i] == i) {` `                ``// Update res``                ``res = Math.max(res, ``1``);``            ``}` `            ``else` `{` `                ``// Count of elements in a subset``                ``int` `count = ``0``;` `                ``// Stores index of elements in``                ``// the current subset``                ``int` `curr_index = i;` `                ``// Calculate length of a subset that``                ``// satisfy the condition``                ``while` `(arr[curr_index]``                       ``!= curr_index) {` `                    ``int` `next_index = arr[curr_index];` `                    ``// Make visited the current index``                    ``arr[curr_index] = curr_index;` `                    ``// Update curr_index``                    ``curr_index = next_index;` `                    ``// Update count``                    ``count++;``                ``}` `                ``// Update res``                ``res = Math.max(res, count);``            ``}``        ``}` `        ``return` `res;``    ``}``}` `// Driver Code``class` `GFG {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``sol st = ``new` `sol();``        ``int``[] arr = { ``5``, ``4``, ``0``, ``3``, ``1``, ``6``, ``2` `};``        ``int` `res = st.arrayNesting(arr);``        ``System.out.println(res);``    ``}``}`

## C#

 `// C# program to implement``// the above approach``using` `System;``class` `sol {` `  ``// Function to find length of longest subset``  ``// such that subset { arr[i], arr[arr[i]], .. }``  ``public` `int` `arrayNesting(``int``[] arr)``  ``{` `    ``// Stores length of the longest subset``    ``// that satisfy the condition``    ``int` `res = 0;` `    ``// Traverse in the array, arr[]``    ``for` `(``int` `i = 0; i < arr.Length; i++) {` `      ``// If arr[i] equals to i``      ``if` `(arr[i] == i) {` `        ``// Update res``        ``res = Math.Max(res, 1);``      ``}` `      ``else` `{` `        ``// Count of elements in a subset``        ``int` `count = 0;` `        ``// Stores index of elements in``        ``// the current subset``        ``int` `curr_index = i;` `        ``// Calculate length of a subset that``        ``// satisfy the condition``        ``while` `(arr[curr_index] != curr_index) {` `          ``int` `next_index = arr[curr_index];` `          ``// Make visited the current index``          ``arr[curr_index] = curr_index;` `          ``// Update curr_index``          ``curr_index = next_index;` `          ``// Update count``          ``count++;``        ``}` `        ``// Update res``        ``res = Math.Max(res, count);``      ``}``    ``}` `    ``return` `res;``  ``}``}` `// Driver Code``class` `GFG {``  ``static` `public` `void` `Main()``  ``{` `    ``sol st = ``new` `sol();``    ``int``[] arr = { 5, 4, 0, 3, 1, 6, 2 };``    ``int` `res = st.arrayNesting(arr);``    ``Console.WriteLine(res);``  ``}``}` `// This code is contributed by Dharanendra L V`

## Python3

 `# Python program for the above approach` `# Function to find length of longest subset``# such that subset { arr[i], arr[arr[i]], .. }``def` `arrayNesting(arr) :` `    ``# Stores length of the longest subset``    ``# that satisfy the condition``    ``res ``=` `0` `    ``# Traverse in the array, arr[]``    ``for` `i ``in` `range``(``len``(arr)) :` `        ``# If arr[i] equals to i``        ``if` `arr[i] ``=``=` `i :``    ` `            ``# Update res``            ``res ``=` `max``(res, ``1``)``    ` `        ``else` `:``    ` `            ``# Count of elements in a subset``            ``count ``=` `0` `            ``# Stores index of elements in``            ``# the current subset``            ``curr_index ``=` `i` `            ``# Calculate length of a subset that``            ``# satisfy the condition``            ``while` `arr[curr_index] !``=` `curr_index :``      ` `                ``next_index ``=` `arr[curr_index]` `                ``# Make visited the current index``                ``arr[curr_index] ``=` `curr_index` `                ``# Update curr_index``                ``curr_index ``=` `next_index` `                ``# Update count``                ``count ``+``=` `1``      ` `        ``# Update res``        ``res ``=` `max``(res, count)``    ``return` `res` `# Driver Code``if` `__name__ ``=``=` `"__main__"` `:``    ` `    ``arr ``=` `[ ``5``, ``4``, ``0``, ``3``, ``1``, ``6``, ``2` `]``    ``res ``=` `arrayNesting(arr)``    ``print``(res)``    ` `    ``# This code is contributed by jana_sayantam..`

## Javascript

 ``
Output:
`4`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up