Cycle Detection in a Directed Graph

Determine if a given directed graph contains a cycle. Return true if at least one cycle is found, otherwise return false.

Input:

T
The first line consists of the integer T, representing the number of test cases.
For each test case, the first line contains two integers V and E.
V is the number of vertices, and E is the number of edges.
The next E lines each comprise two space-separated integers A and B, indicating a directed edge from vertex A to vertex B.

Output:

For every test case, output "true" if a cycle exists in the graph, otherwise show "false".

Example:

Input:
1
4 4
0 1
1 2
2 3
3 1
Output:
true

Explanation: The graph depicted in the example above includes a cycle involving the vertices represented by the edges (1,2), (2,3), and (3,1).

Constraints:

  • 1 <= T <= 10
  • 1 <= V <= 10^3
  • 0 <= E <= 10^3
  • 0 <= A, B < V
  • Time Limit: 1 sec
AnswerBot
4mo

Detect if a directed graph contains a cycle.

  • Use depth-first search (DFS) to detect cycles in the graph.

  • Maintain a visited array to keep track of visited vertices.

  • If a vertex is visited again during DF...read more

Help your peers!
Select
Add answer anonymously...

PayPal Software Engineer interview questions & answers

A Software Engineer was asked 2mo agoQ. Similar to lc921
A Software Engineer was asked 12mo agoQ. Write code to encrypt data.
A Software Engineer was asked 12mo agoQ. Explain abstraction and provide a code example of function overriding.

Popular interview questions of Software Engineer

A Software Engineer was asked 2mo agoQ1. Similar to lc921
A Software Engineer was asked 12mo agoQ2. Write code to encrypt data.
A Software Engineer was asked 12mo agoQ3. Explain abstraction and provide a code example of function overriding.
PayPal Software Engineer 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