Longest chain of arr[i], arr[arr[i]], .. without repetition

Given an array of size n such that elements in array are distinct and in range from 0 to n-1. We need to find out length of the longest chain {arr[i], arr[arr[i]], arr[arr[arr[i]]]……} such that no set element repeats.

Examples:

Input : arr[] = [5, 4, 0, 3, 1, 6, 2]
Output :4
Explanation:
The longest chain without repetition is
{arr[0], arr[5], arr[6], arr[2]} = {5, 6, 2, 0}


Input : arr[] = {1, 0, 4, 2, 3}
Output :3
Explanation:
The longest chain without repetition is
{arr[2], arr[4], arr[3]} = {4, 2, 3}

A naive solution is to find length of longest chain beginning from every element. To keep track of visited nodes, keep a visited array and reset this array after every finding longest chain from an element.



An efficient solution is to traverse each index and set them as -1. Once we see an index that we have set as -1, we know we have come across the same index so we stop and compare if the current count is greater than the max we have seen so far. We can do this setting to -1 in place so that we don’t keep revisiting the same indexes again and again. Why this works is because since each number is distinct, there is always just one way to reach a particular index. So no matter which index you start at in the particular cycle, you will always see the same cycle and hence the same count. So once a cycle is completely visited we can just skip checking for all the indexes in this cycle.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find longest chain of
// arr[i], arr[arr[i]], arr[arr[arr[i]]]
// without repetition.
#include <iostream>
using namespace std;
  
void aNesting(int arr[], int start, int& max)
{
    // Local maximum
    int c_max = 0;
  
    // if current element is not visited then
    // increase c_max by one, set arr[start]
    // and change the start to current value.
    while (arr[start] != -1) {
        c_max++;
        int temp = arr[start];
        arr[start] = -1;
        start = temp;
    }
     
   // if local max is greater than global max 
   // then update global maximum 
   if (c_max > max) max = c_max;
}
  
int maxLength(int arr[], int n)
{
    int max = 0;
    for (int i = 0; i < n; i++) {
        aNesting(arr, i, max);
    }
    return max;
}
  
// Driver code
int main()
{
    int arr[] = { 5, 4, 0, 3, 1, 6, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << maxLength(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find longest chain of
// arr[i], arr[arr[i]], arr[arr[arr[i]]]
// without repetition.
import java.util.*;
  
class solution
{
  
static int aNesting(int arr[], int start, int max)
{
    // Local maximum
    int c_max = 0;
  
    // if current element is not visited then
    // increase c_max by one, set arr[start]
    // and change the start to current value.
    while (arr[start] != -1
    {
        c_max++;
        int temp = arr[start];
        arr[start] = -1;
        start = temp;
    }
      
// if local max is greater than global max 
// then update global maximum 
     if (c_max > max)
      max = c_max;
        
     return max;
  }
  
static int maxLength(int[] arr, int n)
{
    int max = 0,max1;
    for (int i = 0; i < n; i++) 
    {
        max1 = aNesting(arr, i, max);
        if(max1>max)
         max = max1;
    }
    return max;
 }
  
// Driver code
public static void main(String args[])
{
    int arr[] = { 5, 4, 0, 3, 1, 6, 2 };
    int n = arr.length;
    System.out.println(maxLength(arr, n));
}
}
  
// Thi code is contributed by
// Surendra_Gangwar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to find longest chain 
# of arr[i], arr[arr[i]], arr[arr[arr[i]]]
# without repetition.
def aNesting(arr,start, max):
      
    # Local maximum
    c_max = 0
  
    # if current element is not visited then
    # increase c_max by one, set arr[start]
    # and change the start to current value.
    while (arr[start] != -1):
        c_max += 1
        temp = arr[start]
        arr[start] = -1
        start = temp
      
    # if local max is greater than global 
    # max then update global maximum 
    if (c_max > max):
        max = c_max
          
    return max
  
def maxLength(arr, n):
    max = 0
    for i in range(0, n, 1):
        max__ = aNesting(arr, i, max)
        if (max__>max):
            max = max__
    return max__
  
# Driver code
if __name__ =='__main__':
    arr = [5, 4, 0, 3, 1, 6, 2]
    n = len(arr)
    print(maxLength(arr, n))
      
# This code is contributed by
# Shashank_Sharma

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find longest chain of
// arr[i], arr[arr[i]], arr[arr[arr[i]]]
// without repetition.
using System;
  
class GFG
{
  
static int aNesting(int[] arr, int start, int max)
{
    // Local maximum
    int c_max = 0;
  
    // if current element is not visited then
    // increase c_max by one, set arr[start]
    // and change the start to current value.
    while (arr[start] != -1) 
    {
        c_max++;
        int temp = arr[start];
        arr[start] = -1;
        start = temp;
    }
      
    // if local max is greater than global max 
    // then update global maximum 
    if (c_max > max)
    max = c_max;
      
    return max;
}
  
static int maxLength(int[] arr, int n)
{
    int max = 0, max1;
    for (int i = 0; i < n; i++) 
    {
        max1 = aNesting(arr, i, max);
        if(max1>max)
        max = max1;
    }
    return max;
}
  
// Driver code
public static void Main()
{
    int[] arr = { 5, 4, 0, 3, 1, 6, 2 };
    int n = arr.Length;
    Console.WriteLine(maxLength(arr, n));
}
}
  
// Thi code is contributed by
// Akanksha Rai

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find longest chain of
// arr[i], arr[arr[i]], arr[arr[arr[i]]]
// without repetition.
  
function aNesting($arr, $start, &$max)
{
    // Local maximum
    $c_max = 0;
  
    // if current element is not visited then
    // increase c_max by one, set arr[start]
    // and change the start to current value.
    while ($arr[$start] != -1) 
    {
        $c_max++;
        $temp = $arr[$start];
        $arr[$start] = -1;
        $start = $temp;
    }
      
// if local max is greater than global 
// max then update global maximum 
if ($c_max > $max
    $max = $c_max;
}
  
function maxLength($arr, $n)
{
    $max = 0;
    for ($i = 0; $i < $n; $i++)
    {
        aNesting($arr, $i, $max);
    }
    return $max;
}
  
// Driver code
$arr = array(5, 4, 0, 3, 1, 6, 2 );
$n = sizeof($arr);
echo maxLength($arr, $n);
  
// This code is contributed 
// by Akanksha Rai
?>

chevron_right


Output:

4

Time Complexity: O(n)
Auxiliary Space: O(1)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.