Topological Sort Problem Statement
You have a directed acyclic graph (DAG). The task is to determine any topological sorting of this graph.
Explanation:
A Directed Acyclic Graph (DAG) is a graph that has directed edges and no cycles. Topological sorting is a linear ordering of the vertices such that for every directed edge from vertex u
to vertex v
, u
comes before v
in the ordering.
Input:
The first line of input contains an integer ‘T’ representing the number of test cases. For each test case:
- The first line contains two integers, ‘N’ and ‘M’, where ‘N’ is the number of nodes and ‘M’ is the number of edges.
- The following ‘M’ lines each contain two integers, ‘U’ and ‘V’, indicating a directed edge from node ‘U’ to node ‘V’.
Output:
For each test case, output a single line containing N space-separated integers denoting a valid topological sort of the graph. Each test case's output should be on a new line.
Example:
Given the following DAG graph:
Image representation (not shown here)
Possible output topological sort: 1 2 3
Constraints:
- 1 <= T <= 100
- 1 <= N <= 5000
- 0 <= M <= min(5000, (N*(N-1))/2)
- 1 <= U, V <= N and U != V
- Time Limit: 1 second
Note:
You are not required to print the expected output; Just implement the function to return the answer.

AnswerBot
4mo
Implement a function to determine any topological sorting of a directed acyclic graph (DAG).
Create a graph using the given input of nodes and edges
Perform a topological sort on the graph to find a val...read more
Help your peers!
Add answer anonymously...
MindTickle Software Developer Intern interview questions & answers
A Software Developer Intern was asked Q. Is Bipartite Graph Problem You are provided with an undirected graph having 'N' ...read more
A Software Developer Intern was asked Q. Can you design an online Chess Board Game?
A Software Developer Intern was asked Q. Topological Sort Problem Statement You have a directed acyclic graph (DAG). The ...read more
Popular interview questions of Software Developer Intern
A Software Developer Intern was asked Q1. Is Bipartite Graph Problem You are provided with an undirected graph having 'N' ...read more
A Software Developer Intern was asked Q2. Can you design an online Chess Board Game?
A Software Developer Intern was asked Q3. Topological Sort Problem Statement You have a directed acyclic graph (DAG). The ...read more
>
MindTickle Software Developer Intern 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

