
Asked in Amazon
Detect Cycle in a Directed Graph
Determine if a given directed graph contains a cycle. Your function should return true
if the graph contains at least one cycle, and false
otherwise.
Input:
The first line of input contains an integer T, representing the number of test cases.
The first line of each test case consists of two integers, V and E. V represents the number of vertices, and E represents the number of edges in the graph.
The next E lines for each test case describe the edges of the graph, where each edge is given by two integers A and B, indicating a directed edge from vertex A to vertex B.
Output:
For each test case, print "true" if a cycle exists in the graph, otherwise print "false".
Example:
Input:
2
3 3
0 1
1 2
2 0
4 3
0 1
1 2
2 3
Output:
true
false
Constraints:
1 ≤ T ≤ 10
1 ≤ V ≤ 10^3
0 ≤ E ≤ 10^3
0 ≤ A, B < V
Time Limit: 1 sec

AnswerBot
4mo
Detect cycle in a directed graph and return true if cycle exists, false otherwise.
Use Depth First Search (DFS) to detect cycles in the directed graph.
Maintain a visited array to keep track of visited ...read more
Help your peers!
Add answer anonymously...
Top Software Developer Intern Interview Questions Asked at Amazon
Q. What is the code to calculate the distance between two nodes in a binary tree?
Q. Given a tree, find its diameter (the longest path between two nodes in the tree)...read more
Q. For a given array, how would you count the number of inversions?
Interview Questions Asked to Software Developer Intern at Other Companies
Top Skill-Based Questions for Amazon Software Developer Intern
C++ Interview Questions and Answers
300 Questions
Algorithms Interview Questions and Answers
250 Questions
Data Structures Interview Questions and Answers
250 Questions
Web Development Interview Questions and Answers
250 Questions
Operating Systems Interview Questions and Answers
250 Questions
System Design Interview Questions and Answers
250 Questions
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

