Given a directed graph with N vertices and M edges that may contain cycles, the task is to find the lexicographically smallest topological ordering of the graph if it exists otherwise print -1 (if the graph has cycles).
Lexigraphically smallest topological ordering means that if two vertices in a graph do not have any incoming edge then the vertex with the smaller number should appear first in the ordering.
For Example, in the image below many topological orderings are possible e.g 5 2 3 4 0 1, 5 0 2 4 3 1.
But the smallest ordering is 4 5 0 2 3 1.
Output: 4 5 0 2 3 1
Even though 5 4 0 2 3 1 is also a valid topological
ordering of the given graph but it is not
Approach: We will use Kahn’s algorithm for Topological Sorting with a modification. Instead of using a queue we will use a multiset to store the vertices to make sure that every time we pick a vertex it is the smallest possible of all. The overall Time complexity changes to
Below is the implementation of the above approach:
4 5 0 2 3 1
- Find lexicographically smallest string in at most one swaps
- Lexicographically smallest permutation of a string with given subsequences
- Print the lexicographically smallest BFS of the graph starting from 1
- Print the lexicographically smallest DFS of the graph starting from 1
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Lexicographically smallest substring with maximum occurrences containing a's and b's only
- Lexicographically smallest string formed by removing at most one character
- Lexicographically smallest string which differs from given strings at exactly K indices
- Lexicographically smallest K-length substring containing maximum number of vowels
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Topological Sorting
- Find the ordering of tasks from given dependencies
- Kahn's algorithm for Topological Sorting
- All Topological Sorts of a Directed Acyclic Graph
- Topological Sort of a graph using departure time of vertex
- Queries to return the absolute difference between L-th smallest number and the R-th smallest number
- Lexicographically largest string possible in one swap
- Count of lexicographically smaller characters on right
- Lexicographically largest sub-sequence of the given string
- Lexicographically all Shortest Palindromic Substrings from a given string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.