{"id":259,"date":"2025-06-04T15:11:16","date_gmt":"2025-06-04T09:41:16","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=259"},"modified":"2025-06-04T15:17:39","modified_gmt":"2025-06-04T09:47:39","slug":"topo-sort-kahns-algorithm","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/","title":{"rendered":"Topological Sort (Kahn\u2019s Algorithm) \u2013 Simple BFS Solution in Python"},"content":{"rendered":"\n<p>Learn how to perform topological sorting of a DAG using Kahn\u2019s algorithm (BFS based). Clear steps, commented Python code, dry-run example, and Big-O complexity.<\/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 style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-a3f1a0c8-8078-4482-a4f1-7f5b183d369e\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><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<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\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 ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#0-what-does-the-problem-ask\" style=\"\">What does the problem ask?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#1-example\" style=\"\">Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#2-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#3-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#4-code-walkthrough\" style=\"\">Code walkthrough<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#5-dry-run-on-the-sample-graph\" style=\"\">Dry run on the sample graph<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#6-complexity\" style=\"\">Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/topo-sort-kahns-algorithm\/#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>Given a <strong>directed acyclic graph (DAG)<\/strong> with <code>V<\/code> vertices (<code>0 \u2026 V-1<\/code>) and a list of directed edges, return <strong>any order of the vertices<\/strong> such that for every edge <code>u \u2192 v<\/code>, vertex <code>u<\/code> appears <strong>before<\/strong> <code>v<\/code> in the list.<\/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>A correct topological order is <code>5 4 2 3 1 0<\/code>.<br>(Other valid orders are possible.)<\/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<p><strong>Kahn\u2019s algorithm (BFS idea)<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Indegree<\/strong><br><em>For every vertex count how many incoming edges it has.<\/em><br>Vertices with <strong>indegree 0<\/strong> have no prerequisites; they can start the order.<\/li>\n\n\n\n<li><strong>Queue of ready vertices<\/strong><br>Put all indegree-0 vertices in a queue.<\/li>\n\n\n\n<li><strong>Process the queue<\/strong>\n<ul class=\"wp-block-list\">\n<li>Pop a vertex, add it to the answer list.<\/li>\n\n\n\n<li>For each outgoing edge <code>u \u2192 v<\/code>, reduce <code>v<\/code>\u2019s indegree by 1.<\/li>\n\n\n\n<li>If <code>v<\/code>\u2019s indegree becomes 0, push <code>v<\/code> into the queue.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Repeat<\/strong> until the queue is empty.<br>If we output <code>V<\/code> vertices, we have a valid topological order.<br>(If fewer\u2014this would mean the graph had a cycle, but the problem guarantees a DAG.)<\/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\">Code<\/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=\"from collections import deque\n\n\nclass Solution:\n    def topoSort(self, V, edges):\n        adj_list = [[] for _ in range(V)]   # adjacency list\n        indegrees = [0 for _ in range(V)]   # incoming edge counts\n\n        # build graph and indegree array\n        for u, v in edges:                  # edge u \u2192 v\n            adj_list[u].append(v)\n            indegrees[v] += 1\n\n        queue = deque()                     # vertices ready to be processed\n        result = []                         # final topological order\n\n        # add all starting points (indegree == 0)\n        for i in range(V):\n            if indegrees[i] == 0:\n                queue.append(i)\n\n        # BFS over the DAG\n        while queue:\n            current_node = queue.popleft()\n            result.append(current_node)\n\n            # remove current_node\u2019s edges\n            for adjNode in adj_list[current_node]:\n                indegrees[adjNode] -= 1\n                if indegrees[adjNode] == 0:  # new node becomes ready\n                    queue.append(adjNode)\n\n        return result                       # contains V vertices in 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: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> collections <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> deque<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><\/span>\n<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: #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\"># adjacency list<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        indegrees = [<\/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\"># incoming edge counts<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># build graph and indegree array<\/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 style=\"color: #D4D4D4\">            indegrees[v] += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque()                     <\/span><span style=\"color: #6A9955\"># vertices ready to be processed<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        result = []                         <\/span><span style=\"color: #6A9955\"># final topological order<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># add all starting points (indegree == 0)<\/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\">(V):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> indegrees[i] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                queue.append(i)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># BFS over the DAG<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> queue:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            current_node = queue.popleft()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            result.append(current_node)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># remove current_node\u2019s edges<\/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>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                indegrees[adjNode] -= <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> indegrees[adjNode] == <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:  <\/span><span style=\"color: #6A9955\"># new node becomes ready<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append(adjNode)<\/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\"> result                       <\/span><span style=\"color: #6A9955\"># contains V vertices in 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-walkthrough\">Code walkthrough<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Build<\/strong>\n<ul class=\"wp-block-list\">\n<li><code>adj_list[u]<\/code> holds all vertices reachable from <code>u<\/code>.<\/li>\n\n\n\n<li><code>indegrees[v]<\/code> counts how many edges come into <code>v<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Initial queue<\/strong><br>All vertices with no incoming edges can be placed first in the order.<\/li>\n\n\n\n<li><strong>Loop<\/strong>\n<ul class=\"wp-block-list\">\n<li>Take the next ready vertex.<\/li>\n\n\n\n<li>Add it to <code>result<\/code>.<\/li>\n\n\n\n<li>\u201cDelete\u201d its outgoing edges by lowering each neighbor\u2019s indegree.<\/li>\n\n\n\n<li>When a neighbor\u2019s indegree hits 0, push it onto the queue.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Finish<\/strong><br>When the queue is empty, <code>result<\/code> has one valid 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>Step<\/th><th>Queue<\/th><th>Result<\/th><th><code>indegrees<\/code> (key changes)<\/th><\/tr><\/thead><tbody><tr><td>Start<\/td><td><code>[4, 5]<\/code><\/td><td><code>[]<\/code><\/td><td>4\u21920,5\u21920<\/td><\/tr><tr><td>Pop 4<\/td><td><code>[5]<\/code><\/td><td><code>[4]<\/code><\/td><td>0\u21921,1\u21921<\/td><\/tr><tr><td>Process edges 4\u21920, 4\u21921<\/td><td><code>[5]<\/code> (no new zeros)<\/td><td><\/td><td><\/td><\/tr><tr><td>Pop 5<\/td><td><code>[]<\/code><\/td><td><code>[4,5]<\/code><\/td><td>0\u21920,2\u21921<\/td><\/tr><tr><td>Edge 5\u21920 lowers indegree(0) to 0 \u2192 queue <code>[0]<\/code><\/td><td><\/td><td><\/td><td><\/td><\/tr><tr><td>Edge 5\u21922 lowers indegree(2) to 0 \u2192 queue <code>[0,2]<\/code><\/td><td><\/td><td><\/td><td><\/td><\/tr><tr><td>Pop 0<\/td><td><code>[2]<\/code><\/td><td><code>[4,5,0]<\/code><\/td><td>(0 has no children)<\/td><\/tr><tr><td>Pop 2<\/td><td><code>[]<\/code><\/td><td><code>[4,5,0,2]<\/code><\/td><td>3\u21920 \u2192 queue <code>[3]<\/code><\/td><\/tr><tr><td>Pop 3<\/td><td><code>[]<\/code><\/td><td><code>[4,5,0,2,3]<\/code><\/td><td>1\u21920 \u2192 queue <code>[1]<\/code><\/td><\/tr><tr><td>Pop 1<\/td><td><code>[]<\/code><\/td><td><code>[4,5,0,2,3,1]<\/code><\/td><td>done<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Final order: <code>4 5 0 2 3 1<\/code> \u2014valid.<\/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>We look at each vertex and each edge once. We store the adjacency list (<code>E<\/code>) and two arrays of size <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=\"7-conclusion\">Conclusion<\/h2>\n\n\n\n<p>Kahn\u2019s algorithm uses a simple queue and indegree counts to produce a topological order with breadth-first style processing. It is intuitive, runs in linear time, and is often the first choice for scheduling tasks with dependencies.<\/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\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to perform topological sorting of a DAG using Kahn\u2019s algorithm (BFS based). Clear steps, commented Python code, dry-run example, and Big-O complexity. Here&#8217;s the [Problem Link] to begin with. What does the problem ask? Given a directed acyclic graph (DAG) with V vertices (0 \u2026 V-1) and a list of directed edges, return<\/p>\n","protected":false},"author":1,"featured_media":260,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[21,17,19],"class_list":{"0":"post-259","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-bfs","10":"tag-graph","11":"tag-medium"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/topo-sort-using-kahns-algo-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\/259","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=259"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/259\/revisions"}],"predecessor-version":[{"id":263,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/259\/revisions\/263"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/260"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=259"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=259"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=259"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}