Minimum Number of Vertices to Reach All Nodes Problem Statement
In a directed acyclic graph with 'N' nodes, given a matrix 'edges' of size M x 2 representing 'M' edges where each edge is directed from node edges[i][0] to node edges[i][1], find the smallest set of vertices from which all the nodes in the graph are reachable.
Input:
The first line contains a single integer ‘T’, denoting the number of test cases.
The first line of each test case contains two integers ‘N’ and ‘M’, where ‘N’ represents the number of vertices and ‘M’ denotes the number of edges.
The next ‘M’ lines of each test case contain two integers ‘X’ and ‘Y’, where ‘X’ is the start vertex and ‘Y’ is the end vertex of a directed edge.
Output:
For each test case, output the smallest set of vertices from which all the nodes in the graph are reachable, in sorted order.
Print each test case result on a new line.
Example:
Sample Input:
2
6 5
0 1
0 2
2 5
3 4
4 2
5 4
0 1
2 1
1 4
2 4
Sample Output:
0 3
0 2 3
Explanation of Sample Output:
In the first test case, the vertices 0 and 3 can collectively reach all other nodes in the graph.
In the second test case, the vertices 0, 2, and 3 can collectively reach all nodes.
Constraints:
- 1 ≤ T ≤ 5
- 2 ≤ N ≤ 105
- 1 ≤ M ≤ 105
- 0 ≤ X, Y ≤ N - 1
- Time Limit: 1 second
Note:
Nodes are numbered from 0 to N - 1.
The provided graph is connected.
Vertices in the result should be printed in sorted order.

AnswerBot
4mo
The problem involves finding the smallest set of vertices from which all nodes in a directed acyclic graph are reachable.
Create a directed graph using the given edges.
Perform a topological sort to fin...read more
Help your peers!
Add answer anonymously...
Morgan Stanley Technology Analyst interview questions & answers
A Technology Analyst was asked Q. Explain the Bubble Sort algorithm.
A Technology Analyst was asked Q. Given a number, print it in words.
A Technology Analyst was asked Q. Flatten a Multilevel Sorted Linked List You are given a linked list with 'N' nod...read more
Popular interview questions of Technology Analyst
A Technology Analyst was asked Q1. Explain the Bubble Sort algorithm.
A Technology Analyst was asked Q2. Given a number, print it in words.
A Technology Analyst was asked Q3. Flatten a Multilevel Sorted Linked List You are given a linked list with 'N' nod...read more
>
Morgan Stanley Technology Analyst Interview 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

