VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-chain-of-arri-arrarri-without-repetition/

⇱ Longest chain of arr[i], arr[arr[i]], .. without repetition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 30 Aug, 2022

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.

Implementation:


Output
4

Complexity Analysis:

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