Largest Cycle in Maze Problem Statement

Given a maze represented by 'N' cells numbered from 0 to N-1, and an array arr of 'N' integers where arr[i] denotes the cell number that can be reached from the 'i'-th cell in one step, identify the length of the largest cycle in the maze.

Note that each cell may have ≤ 1 exit but can have multiple entry points. Cells may have self-cycles (a cycle of length 1). If arr[i] = -1, it means the 'i'-th cell has no exit.

Example:

Input:
T = 2
N = 5
arr = [2, -1, 0, 4, 5]
N = 6
arr = [-1, 0, 1, 2, 3, -1]
Output:
3
-1
Explanation:

In the first test case, there is a cycle 0 -> 2 -> 0 with length 3. In the second test case, there are no cycles.

Constraints:

  • 1 ≤ T ≤ 50
  • 1 ≤ N ≤ 10,000
  • -1 ≤ arr[i] < N-1
Note:
For each test case, output the length of the largest cycle in the maze or -1 if no cycles exist. Print the output for each test case on a new line.
AnswerBot
4mo

Identify the length of the largest cycle in a maze represented by cells and an array of integers.

  • Iterate through each cell and find the cycle length using DFS or Floyd's Tortoise and Hare algorithm.

  • Ha...read more

Help your peers!
Select
Add answer anonymously...

JUSPAY Software Developer interview questions & answers

A Software Developer was asked 1mo agoQ. What is a multithreaded environment, and how would you develop an application th...read more
A Software Developer was asked Q. Ninja and the Maze Problem Statement Ninja is stuck in a maze represented as a 2...read more
A Software Developer was asked Q. Largest Cycle in Maze Problem Statement Given a maze represented by 'N' cells nu...read more

Popular interview questions of Software Developer

A Software Developer was asked 1mo agoQ1. What is a multithreaded environment, and how would you develop an application th...read more
A Software Developer was asked Q2. Ninja and the Maze Problem Statement Ninja is stuck in a maze represented as a 2...read more
A Software Developer was asked Q3. Largest Cycle in Maze Problem Statement Given a maze represented by 'N' cells nu...read more
JUSPAY Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits