# Array Nesting in C++

C++Server Side ProgrammingProgramming

Suppose we have a zero-indexed array A of length N that contains all integers from 0 to N-1. We have to find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Now consider the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. So if the array is like A = [5,4,0,3,1,6,2], then the output will be 4, as A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, and finally A[6] = 2.

To solve this, we will follow these steps −

• So create a function called dfs. This will take node, arr array, v array, and a set visited. Do the following in dfs array −
• if node is visited, then return
• insert node into v, mark node as visited
• dfs(arr[node], arr, v, visited)
• From the main method, do the following −
• ret := 0, n := size of nums. make a set called visited
• for i in range 0 to n – 1
• create an array v
• if nums[i] is not visited, then dfs(nums[i], nums, v, visited)
• ret := max of ret and size of v
• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void dfs(int node, vector <int>& arr, vector <int>& v, set <int>& visited){
if(visited.count(node)) return;
v.push_back(node);
visited.insert(node);
dfs(arr[node], arr, v, visited);
}
int arrayNesting(vector<int>& nums) {
int ret = 0;
int n = nums.size();
set <int> visited;
for(int i = 0; i < n; i++){
vector <int> v;
if(!visited.count(nums[i]))dfs(nums[i], nums, v, visited);
ret = max(ret, (int)v.size());
}
return ret;
}
};
main(){
vector<int> v = {5,4,0,3,1,6,2};
Solution ob;
cout << (ob.arrayNesting(v));
}

## Input

[5,4,0,3,1,6,2]

## Output

4
Updated on 04-May-2020 13:12:17