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 integersV
andE
.
V is the number of vertices, and E is the number of edges.
The next E lines each comprise two space-separated integersA
andB
, indicating a directed edge from vertexA
to vertexB
.
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!
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.
Stay ahead in your career. Get AmbitionBox app


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
AmbitionBox Awards
Get AmbitionBox app

