{"id":373,"date":"2025-06-24T23:11:45","date_gmt":"2025-06-24T17:41:45","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=373"},"modified":"2025-06-26T22:01:11","modified_gmt":"2025-06-26T16:31:11","slug":"cheapest-flights-within-k-stops-leetcode-787","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/","title":{"rendered":"Cheapest Flights Within K Stops | Leetcode 787 | Easy BFS Approach in Python"},"content":{"rendered":"\n<p>Solve \u201cCheapest Flights Within K Stops\u201d (LeetCode 787) in plain Python using a BFS queue and a cost array. Learn the intuition, code, and dry-run for cheapest flights first-time success.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/cheapest-flights-within-k-stops\/description\/\" 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-0a4e3ff9-1831-45cb-a212-90428f2a7dcc\" 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\/cheapest-flights-within-k-stops-leetcode-787\/#0-1-what-does-the-problem-ask\" style=\"\">1. What does the problem ask?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#1-2-quick-examples\" style=\"\">2. Quick examples<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#2-3-intuition-amp-approach\" style=\"\">3. Intuition &amp; approach<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#3-31-graph-view\" style=\"\">3.1 Graph view<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#4-32-why-not-plain-dijkstra\" style=\"\">3.2 Why not plain Dijkstra?<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#5-33-bfs-with-cost-pruning\" style=\"\">3.3 BFS with cost pruning<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#6-4-code\" style=\"\">4 Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#7-5-step-by-step-explanation\" style=\"\">5. Step-by-step explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#8-6-dry-run-tiny-graph\" style=\"\">6. Dry run (tiny graph)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#9-7-complexity\" style=\"\">7. Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/cheapest-flights-within-k-stops-leetcode-787\/#10-8-conclusion\" style=\"\">8. Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-1-what-does-the-problem-ask\">1. What does the problem ask?<\/h2>\n\n\n\n<p><em>You have<\/em> <strong><code>n<\/code><\/strong> cities numbered <code>0 \u2026 n-1<\/code> and a list of flights<br><code>[from, to, price]<\/code>.<br>You must fly from <strong><code>src<\/code><\/strong> to <strong><code>dst<\/code><\/strong> but may take <strong>at most <code>k<\/code> intermediate stops<\/strong><br>(so at most <code>k + 1<\/code> flights in total).<\/p>\n\n\n\n<p>Return <strong>the cheapest possible price<\/strong>.<br>If no such route exists, return <strong><code>-1<\/code><\/strong>.<\/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-2-quick-examples\">2. Quick examples<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th><code>n<\/code><\/th><th><code>flights<\/code><\/th><th><code>src<\/code> \u2192 <code>dst<\/code>, <code>k<\/code><\/th><th>Answer<\/th><th>Why<\/th><\/tr><\/thead><tbody><tr><td>3<\/td><td><code>[[0,1,100],[1,2,100],[0,2,500]]<\/code><\/td><td><code>0\u21922<\/code>, <code>k=1<\/code><\/td><td><code>200<\/code><\/td><td>0\u21921\u21922 costs 200 (1 stop).<\/td><\/tr><tr><td>3<\/td><td>same flights<\/td><td><code>0\u21922<\/code>, <code>k=0<\/code><\/td><td><code>500<\/code><\/td><td>Only direct flight allowed.<\/td><\/tr><tr><td>4<\/td><td><code>[[0,1,100],[1,2,100],[2,3,100],[0,3,500]]<\/code><\/td><td><code>0\u21923<\/code>, <code>k=1<\/code><\/td><td><code>500<\/code><\/td><td>Cheapest path needs 2 stops, which exceeds <code>k<\/code>.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-3-intuition-amp-approach\">3. Intuition &amp; approach<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-31-graph-view\">3.1 Graph view<\/h3>\n\n\n\n<p>Cities are nodes; flights are <strong>directed edges<\/strong> with weights = prices.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-32-why-not-plain-dijkstra\">3.2 Why not plain Dijkstra?<\/h3>\n\n\n\n<p>Dijkstra does not limit the <strong>number of edges<\/strong>; it might return a cheaper path that uses too many stops.<br>We need a structure that also keeps track of <strong>how many flights<\/strong> we have taken so far.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"5-33-bfs-with-cost-pruning\">3.3 BFS with cost pruning<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Level = stops so far<\/strong><br>A standard BFS queue processes nodes layer by layer; here each layer means \u201cone more flight taken\u201d.<\/li>\n\n\n\n<li><strong>State tuple<\/strong> <code>(stopsUsed, city, costSoFar)<\/code><br>We never push a state whose <code>stopsUsed<\/code> already exceeded <code>k + 1<\/code> flights.<\/li>\n\n\n\n<li><strong><code>min_cost[city]<\/code> array<\/strong><br>Stores the cheapest price found so far for that city <strong>with any number of stops \u2264 k + 1<\/strong>.<br>We only push a new state if we have really improved that city\u2019s cost.<\/li>\n\n\n\n<li><strong>Stop early<\/strong><br>We may still keep exploring even after seeing <code>dst<\/code> once, because another path with the same or fewer stops could be cheaper\u2014but the <code>min_cost<\/code> check prevents endless work.<\/li>\n<\/ol>\n\n\n\n<p>This idea is similar to <strong>Bellman-Ford limited to <code>k + 1<\/code> rounds<\/strong>, but implemented with a queue for clarity.<\/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-4-code\">4 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=\"import sys\nfrom collections import deque\nfrom typing import List\n\n\nclass Solution:\n    def findCheapestPrice(\n        self, n: int, flights: List[List[int]], src: int, dst: int, k: int\n    ) -&gt; int:\n        # build adjacency list: u -&gt; [(v, price), ...]\n        adj_list = [[] for _ in range(n)]\n        for u, v, cost in flights:\n            adj_list[u].append([v, cost])\n\n        # cost array \u2013 start city = 0, others = +\u221e\n        min_cost = [sys.maxsize for _ in range(n)]\n        min_cost[src] = 0\n\n        # BFS queue holds (stopsUsed, city, costSoFar)\n        queue = deque()\n        queue.append([0, src, 0])\n\n        while queue:\n            stops, city, cost = queue.popleft()\n\n            # Explore outward flights\n            for nxt, price in adj_list[city]:\n                new_cost  = cost + price\n                new_stops = stops + 1       # we have used one more flight\n\n                # Respect stop limit: total flights \u2264 k + 1\n                if new_stops == k + 1 and nxt != dst:\n                    continue\n\n                # Relaxation: only continue if cheaper\n                if new_cost &lt; min_cost[nxt]:\n                    min_cost[nxt] = new_cost\n                    queue.append([new_stops, nxt, new_cost])\n\n        return -1 if min_cost[dst] == sys.maxsize else min_cost[dst]\" 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\">import<\/span><span style=\"color: #D4D4D4\"> sys<\/span><\/span>\n<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 style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> typing <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> List<\/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\">findCheapestPrice<\/span><span style=\"color: #D4D4D4\">(<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">n<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">flights<\/span><span style=\"color: #D4D4D4\">: List[List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">]], <\/span><span style=\"color: #9CDCFE\">src<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">dst<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">k<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    ) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># build adjacency list: u -&gt; [(v, price), ...]<\/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\">(n)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> u, v, cost <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> flights:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            adj_list[u].append([v, cost])<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># cost array \u2013 start city = 0, others = +\u221e<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        min_cost = [sys.maxsize <\/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\">(n)]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        min_cost[src] = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># BFS queue holds (stopsUsed, city, costSoFar)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue.append([<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, src, <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">])<\/span><\/span>\n<span class=\"line\"><\/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\">            stops, city, cost = queue.popleft()<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Explore outward flights<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> nxt, price <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> adj_list[city]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                new_cost  = cost + price<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                new_stops = stops + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">       <\/span><span style=\"color: #6A9955\"># we have used one more flight<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Respect stop limit: total flights \u2264 k + 1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> new_stops == k + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">and<\/span><span style=\"color: #D4D4D4\"> nxt != dst:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># Relaxation: only continue if cheaper<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> new_cost &lt; min_cost[nxt]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    min_cost[nxt] = new_cost<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    queue.append([new_stops, nxt, new_cost])<\/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\"> -<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> min_cost[dst] == sys.maxsize <\/span><span style=\"color: #C586C0\">else<\/span><span style=\"color: #D4D4D4\"> min_cost[dst]<\/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=\"7-5-step-by-step-explanation\">5. Step-by-step explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Adjacency list<\/strong> gives O(1) access to outgoing flights.<\/li>\n\n\n\n<li><strong><code>min_cost<\/code><\/strong> prevents revisiting a city with a worse or equal total price.<\/li>\n\n\n\n<li><strong><code>stops<\/code> counter<\/strong> ensures we never exceed <code>k + 1<\/code> flights.<\/li>\n\n\n\n<li><strong>When queue empties<\/strong>, every path with \u2264 <code>k<\/code> stops has been tried; <code>min_cost[dst]<\/code> is the answer.<\/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=\"8-6-dry-run-tiny-graph\">6. Dry run (tiny graph)<\/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=\"n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]]\nsrc = 0, dst = 2, k = 1\" 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\">n = <\/span><span style=\"color: #B5CEA8\">3<\/span><span style=\"color: #D4D4D4\">, flights = [[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">],[<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">100<\/span><span style=\"color: #D4D4D4\">],[<\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #B5CEA8\">500<\/span><span style=\"color: #D4D4D4\">]]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">src = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">, dst = <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">, k = <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Pop <code>(stops,city,cost)<\/code><\/th><th>Push states<\/th><th><code>min_cost<\/code><\/th><\/tr><\/thead><tbody><tr><td>(0,0,0)<\/td><td>(1,1,100), (1,2,500)<\/td><td><code>[0,100,500]<\/code><\/td><\/tr><tr><td>(1,1,100)<\/td><td>(2,2,200) \u2013 allowed, stops=2&gt;k+1? no (k+1=2)<\/td><td><code>[0,100,200]<\/code><\/td><\/tr><tr><td>(1,2,500)<\/td><td>\u2013<\/td><td>no change<\/td><\/tr><tr><td>(2,2,200)<\/td><td>\u2013<\/td><td>final<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Cheapest price found = <strong>200<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"9-7-complexity\">7. Complexity<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Metric<\/th><th>Big-O<\/th><th>Notes<\/th><\/tr><\/thead><tbody><tr><td><strong>Time<\/strong><\/td><td><code>O((V + E) log V)<\/code> worst-case, but with early pruning it is usually faster. Each edge can be relaxed at most once for each stop level.<\/td><td><\/td><\/tr><tr><td><strong>Space<\/strong><\/td><td><code>O(V + E)<\/code><\/td><td>Adjacency list + queue + cost array.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><code>V = n<\/code>, <code>E = len(flights)<\/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=\"10-8-conclusion\">8. Conclusion<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Cheapest Flights Within K Stops<\/strong> is best tackled by a <strong>BFS-style traversal<\/strong> that tracks both price and stops.<\/li>\n\n\n\n<li>A simple queue plus a <code>min_cost<\/code> array avoids the heavier Bellman-Ford double loop.<\/li>\n\n\n\n<li>Remember the key SEO phrase, <strong>cheapest flights<\/strong>\u2014and this quick Dijkstra-inspired idea to keep your interview path cost-effective!<\/li>\n<\/ul>\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:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\">Join our 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>Solve \u201cCheapest Flights Within K Stops\u201d (LeetCode 787) in plain Python using a BFS queue and a cost array. Learn the intuition, code, and dry-run for cheapest flights first-time success. Here&#8217;s the [Problem Link] to begin with. 1. What does the problem ask? You have n cities numbered 0 \u2026 n-1 and a list of<\/p>\n","protected":false},"author":1,"featured_media":387,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[21,17,18],"class_list":{"0":"post-373","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-bfs","10":"tag-graph","11":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/06\/cheapest-flights-with-k-stops-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\/373","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=373"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/373\/revisions"}],"predecessor-version":[{"id":390,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/373\/revisions\/390"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/387"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=373"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=373"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=373"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}