Largest Cycle
You are given a maze consisting of N cells numbered from 0 to N - 1 and an array ‘arr’ of N integers in which arr[i] contains the cell number that can be reached from ‘i’th cell in one step. You are supposed to find the length of the largest cycle in the maze, given that each cell has less than or equal to 1 exit but can have multiple entry points.
Note:
The maze may contain self-cycles.
arr[i] = -1 means the ‘i’th cell doesn’t have an exit.
Input Format:
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains integer ‘N’, which denotes the number of cells in the maze.
The second line contains N integers, denoting the elements of the array ‘arr’.
Output Format:
For each test case, print the length of the largest cycle in the maze and -1 if there are no cycles.
Print the output of each test case in a separate line.
Constraints:
1<= T <= 50
1 <= N <= 10,000
-1 <= arr[i] <= N-1
Where ’T’ is the number of test cases, and N denotes the number of cells in the maze and arr[i] is the cell that can be reached from ‘i’th cell.
Time Limit: 1 sec
CodingNinjas
author
2y
DFS
The idea is to do a depth-first search to find all the cycles which are formed and calculate the length of the largest cycle. We are treating the array as a graph of directed edges. Whenever we get...read more
Help your peers!
Add answer anonymously...
Top JUSPAY Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app