Topological Sort Problem Statement

You are given a directed acyclic graph (DAG). Your task is to perform topological sorting of the graph and return any valid ordering.

Explanation:

A directed acyclic graph is a graph without cycles where edges have a direction. In a topological sort of the DAG, every directed edge from node U to node V ensures that U comes before V in the ordering.

Example:

Consider the following DAG:

DAG Example

One possible topological sorting of this graph is:

1 2 3

Input:

The first line contains an integer ‘T’ for the number of test cases.
Each test case starts with two integers ‘N’ (number of nodes) and ‘M’ (number of edges).
The following ‘M’ lines each contain a pair of integers ‘U’ and ‘V’, indicating a directed edge from ‘U’ to ‘V’.

Output:

For each test case, output a line with ‘N’ space-separated integers that represent a topological sort of the graph. Each test case's result should be printed on a new line.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 5000
  • 0 <= M <= min(5000, (N*(N-1))/2)
  • 1 <= U, V <= N and U != V

Note: You don’t need to print the output, only implement the function to return the answer.

AnswerBot
4mo

Implement a function to perform topological sorting on a directed acyclic graph (DAG) and return any valid ordering.

  • Create a graph representation using adjacency list or matrix

  • Perform depth-first sear...read more

Help your peers!
Select
Add answer anonymously...

Top Software Engineer Interview Questions Asked at Bounteous x Accolite

Q. What is your understanding of OOPS concepts?
Q. How do you check for a loop in a linked list?
Q. Write a function to detect if a given linked list is circular or not.
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