{"id":251,"date":"2025-06-03T15:43:48","date_gmt":"2025-06-03T10:13:48","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=251"},"modified":"2025-06-03T15:43:49","modified_gmt":"2025-06-03T10:13:49","slug":"topological-sort-in-graph","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/","title":{"rendered":"Topological Sort in Graph | Simple DFS + Stack Solution in Python"},"content":{"rendered":"\n<p>Learn how to find a topological sort of a directed acyclic graph (DAG) using depth-first search (DFS) and a stack. Clear intuition, step-by-step guide, commented Python code, dry run, and Big-O analysis.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/www.geeksforgeeks.org\/problems\/topological-sort\/1\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div class=\"wp-block-ub-table-of-contents-block ub_table-of-contents\" id=\"ub_table-of-contents-bfbc07d6-3f03-4260-8a29-3b886e737f8b\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"false\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"true\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column \">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#0-what-does-the-problem-ask\" style=\"\">What does the problem ask?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#1-example\" style=\"\">Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#2-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#3-code-original-lines-kept-only-comments-added\" style=\"\">Code (original lines kept, only comments added)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#4-code-explanation-step-by-step\" style=\"\">Code explanation (step-by-step)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#5-dry-run-on-the-sample-graph\" style=\"\">Dry run on the sample graph<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#6-complexity\" style=\"\">Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topological-sort-in-graph\/#7-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-does-the-problem-ask\">What does the problem ask?<\/h2>\n\n\n\n<p>You are given a <strong>directed acyclic graph (DAG)<\/strong> with <code>V<\/code> vertices (numbered <code>0\u2026V-1<\/code>) and a list of directed edges.<br>Your task is to return <strong>any valid topological ordering<\/strong> of the vertices, an ordering where every edge <code>u \u2192 v<\/code> appears with <code>u<\/code> <strong>before<\/strong> <code>v<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-example\">Example<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"V = 6\nEdges = [\n  (5, 0), (5, 2),\n  (4, 0), (4, 1),\n  (2, 3), (3, 1)\n]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">V = <\/span><span style=\"color: #B5CEA8\">6<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">Edges = [<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  (<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">5<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  (<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">),<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  (<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">), (<\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>One correct topological order is<br><code>5 4 2 3 1 0<\/code><\/p>\n\n\n\n<p>Other valid orders exist; any that respect all edge directions is accepted.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-intuition-amp-approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>DFS explores forward edges.<\/strong><br>When DFS finishes exploring a node, all its outgoing neighbors are already placed somewhere <strong>before<\/strong> we push that node onto a stack.<\/li>\n\n\n\n<li><strong>Stack collects finished nodes.<\/strong><br>After we visit every node reachable from the start, we push the start node onto the stack.<\/li>\n\n\n\n<li><strong>Reverse the stack.<\/strong><br>If we pop elements (or simply reverse the stack list) we get a sequence where every parent appears before its children, exactly what we need.<\/li>\n\n\n\n<li><strong>Handle every component.<\/strong><br>The graph can have more than one disconnected part, so we start DFS from every unvisited vertex.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-code-original-lines-kept-only-comments-added\">Code (original lines kept, only comments added)<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    # DFS helper: visit node, then its children, then push node to stack\n    def dfs(self, current_node, visited, stack, adj_list):\n        visited[current_node] = 1                # mark as visited\n        for adjNode in adj_list[current_node]:   # explore all outgoing edges\n            if visited[adjNode] == 0:\n                self.dfs(adjNode, visited, stack, adj_list)\n        stack.append(current_node)               # post-order push\n\n    def topoSort(self, V, edges):\n        adj_list = [[] for _ in range(V)]        # build adjacency list\n        for u, v in edges:                       # edge u \u2192 v\n            adj_list[u].append(v)\n\n        stack = []\n        visited = [0 for _ in range(V)]          # 0 = not visited\n        for i in range(0, V):                    # check every vertex\n            if visited[i] == 0:\n                self.dfs(i, visited, stack, adj_list)\n\n        return stack[::-1]                       # reverse = topo order\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #6A9955\"># DFS helper: visit node, then its children, then push node to stack<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">dfs<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">current_node<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">visited<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">stack<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">adj_list<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited[current_node] = <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># mark as visited<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> adjNode <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj_list[current_node]:   <\/span><span style=\"color: #6A9955\"># explore all outgoing edges<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> visited[adjNode] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.dfs(adjNode, visited, stack, adj_list)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack.append(current_node)               <\/span><span style=\"color: #6A9955\"># post-order push<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">topoSort<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">V<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">edges<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        adj_list = [[] <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(V)]        <\/span><span style=\"color: #6A9955\"># build adjacency list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> u, v <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> edges:                       <\/span><span style=\"color: #6A9955\"># edge u \u2192 v<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            adj_list[u].append(v)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        stack = []<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        visited = [<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> _ <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(V)]          <\/span><span style=\"color: #6A9955\"># 0 = not visited<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, V):                    <\/span><span style=\"color: #6A9955\"># check every vertex<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> visited[i] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.dfs(i, visited, stack, adj_list)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> stack[::-<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">]                       <\/span><span style=\"color: #6A9955\"># reverse = topo order<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-code-explanation-step-by-step\">Code explanation (step-by-step)<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Adjacency list<\/strong> \u2013 converts edge pairs into lists for quick lookup.<\/li>\n\n\n\n<li><strong><code>visited<\/code> array<\/strong> \u2013 keeps us from visiting a node twice.<\/li>\n\n\n\n<li><strong>Outer loop<\/strong> \u2013 starts DFS from any node still unvisited (covers all components).<\/li>\n\n\n\n<li><strong>Inside <code>dfs()<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li>Mark node visited.<\/li>\n\n\n\n<li>Recursively visit each neighbor.<\/li>\n\n\n\n<li>After children are done, push the node onto <code>stack<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Return<\/strong> reversed <code>stack<\/code> for the final topological order.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-dry-run-on-the-sample-graph\">Dry run on the sample graph<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Action<\/th><th><code>stack<\/code> (bottom \u2192 top)<\/th><th><code>visited<\/code><\/th><\/tr><\/thead><tbody><tr><td>Start DFS at <code>0<\/code>? No, unreachable yet<\/td><td><code>[]<\/code><\/td><td>\u2026<\/td><\/tr><tr><td>Start DFS at <code>1<\/code>? reachable later<\/td><td><\/td><td><\/td><\/tr><tr><td>Start at <code>2<\/code>? No, will hit via <code>5<\/code><\/td><td><\/td><td><\/td><\/tr><tr><td>Start at <code>3<\/code>? No<\/td><td><\/td><td><\/td><\/tr><tr><td><strong>Start at <code>4<\/code><\/strong><\/td><td><\/td><td>mark 4<\/td><\/tr><tr><td>Visit <code>0<\/code> \u2192 push <code>0<\/code><\/td><td><code>[0]<\/code><\/td><td>mark 0<\/td><\/tr><tr><td>Visit <code>1<\/code> \u2192 push <code>1<\/code><\/td><td><code>[0,1]<\/code><\/td><td>mark 1<\/td><\/tr><tr><td>Push <code>4<\/code><\/td><td><code>[0,1,4]<\/code><\/td><td><\/td><\/tr><tr><td><strong>Start at <code>5<\/code><\/strong><\/td><td><\/td><td>mark 5<\/td><\/tr><tr><td>Visit <code>0<\/code> (already done)<\/td><td><\/td><td><\/td><\/tr><tr><td>Visit <code>2<\/code><\/td><td><\/td><td>mark 2<\/td><\/tr><tr><td>Visit <code>3<\/code><\/td><td><\/td><td>mark 3<\/td><\/tr><tr><td>Visit <code>1<\/code> (done)<\/td><td><\/td><td><\/td><\/tr><tr><td>Push <code>3<\/code><\/td><td><code>[0,1,4,3]<\/code><\/td><td><\/td><\/tr><tr><td>Push <code>2<\/code><\/td><td><code>[0,1,4,3,2]<\/code><\/td><td><\/td><\/tr><tr><td>Push <code>5<\/code><\/td><td><code>[0,1,4,3,2,5]<\/code><\/td><td><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Reverse \u2192 <code>5 2 3 4 1 0<\/code> (also valid).<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-complexity\">Complexity<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Measure<\/th><th>Value<\/th><\/tr><\/thead><tbody><tr><td><strong>Time<\/strong><\/td><td><strong>O(V + E)<\/strong><\/td><\/tr><tr><td><strong>Space<\/strong><\/td><td><strong>O(V + E)<\/strong><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><em>Reason<\/em><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>We visit each vertex once and scan each edge once \u2192 <code>V + E<\/code>.<\/li>\n\n\n\n<li>Adjacency list and recursion stack together store up to <code>V + E<\/code> items.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-conclusion\">Conclusion<\/h2>\n\n\n\n<p>Topological sorting of a DAG can be done easily with DFS:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Build an adjacency list.<\/li>\n\n\n\n<li>Perform a post-order DFS, pushing nodes onto a stack after visiting children.<\/li>\n\n\n\n<li>Reverse the stack to get a valid ordering.<\/li>\n<\/ol>\n\n\n\n<p>The method is linear, simple, and works for any directed acyclic graph.<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/master-dsa-with-leetcode\" target=\"_blank\" rel=\"noreferrer noopener\">Join our FREE Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to find a topological sort of a directed acyclic graph (DAG) using depth-first search (DFS) and a stack. Clear intuition, step-by-step guide, commented Python code, dry run, and Big-O analysis. Here&#8217;s the [Problem Link] to begin with. What does the problem ask? You are given a directed acyclic graph (DAG) with V vertices<\/p>\n","protected":false},"author":1,"featured_media":253,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,4],"tags":[8,17],"class_list":{"0":"post-251","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-beginner","9":"tag-easy","10":"tag-graph"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/topo-sort-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/251","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=251"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/251\/revisions"}],"predecessor-version":[{"id":256,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/251\/revisions\/256"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/253"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=251"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=251"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}