The O(n) Club: Cheapest Flights Within K Stops – Layovers, Logic, and Code Turbulence
⚡ TL;DR
Want the cheapest ticket from A to B with no more than K layovers? Try every possible flight combo if you hate free time or flex your Bellman-Ford muscles right. Here’s a sneak peek (Java, naturally):
// Brute-ish but gets the point: int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { int[] cost = new int[n]; Arrays.fill(cost, Integer.MAX_VALUE); cost[src] = 0; for (int i = 0; i <= K; i++) { int[] temp = Arrays.copyOf(cost, n); for (int[] f : flights) { int u = f[0], v = f[1], w = f[2]; if (cost[u] != Integer.MAX_VALUE) temp[v] = Math.min(temp[v], cost[u] + w); } cost = temp; } return cost[dst] == Integer.MAX_VALUE ? -1 : cost[dst]; }
🧠 How Devs Usually Mess This Up
Welcome to the league of Almost Right™:
🔍 What’s Actually Going On
Flight search, but with rules. Picture a world map where airlines charge like road tolls, and you only get K bathroom breaks (aka layovers) on your trip—or Mom gets mad. Bellman-Ford runs an annual Sale: Every ‘iteration’ is a shot to add another flight to your itinerary, but only if it fits the layover budget.
Think of the cost array like your itinerary list: use yesterday’s version for each update, or you’ll sneak in extra stops and get mugged by the algorithmic TSA.
🛠️ PseudoCode
- Start with all flights overpriced (∞), except your home airport (0):
Because staying home costs nothing unless you count dignity. - Do K+1 rounds (flights):
- Make a backup of current least-cost array.
- For every flight u → v costing w:
- If you could get to u in ≤ current cost, see if v is cheaper via u + w.
- Only update the backup! No time travel allowed.
- After the round, backup is the new base. Lather, rinse, repeat.
- Endgame: If you ever reach your destination, congrats! Otherwise, consider carrier pigeons.
- Java flavor:
// See TL;DR above. Highlight: Bellman-Ford, but capped at K+1 rounds.
💻 The Code
import java.util.*;
public class CheapestFlights {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
int[] cost = new int[n];
Arrays.fill(cost, Integer.MAX_VALUE);
cost[src] = 0;
for (int i = 0; i <= k; i++) {
int[] next = Arrays.copyOf(cost, n);
for (int[] f : flights) {
int u = f[0], v = f[1], w = f[2];
if (cost[u] != Integer.MAX_VALUE && cost[u] + w < next[v]) {
next[v] = cost[u] + w;
}
}
cost = next;
}
return cost[dst] == Integer.MAX_VALUE ? -1 : cost[dst];
}
public static void main(String[] args) {
CheapestFlights cf = new CheapestFlights();
int[][] flights = { {0,1,100}, {1,2,100}, {0,2,500} };
System.out.println(cf.findCheapestPrice(3, flights, 0, 2, 1)); // 200
System.out.println(cf.findCheapestPrice(3, flights, 0, 2, 0)); // 500
}
}
⚠️ Pitfalls, Traps & Runtime Smacks
- Negative flight cost? Bellman-Ford isn’t fazed, but your travel agent might be.
- No solution? Return -1 (no, hiking isn’t supported).
- K = 0? Only nonstop flights or bust. Hope you packed snacks.
- Forgetting to copy cost arrays: Extra stops sneak in. Interviewers sigh.
- Time/space: O(K*E) time, O(N) space. Like waiting in airport security, but you know it ends.
🧠 Interviewer Brain-Tattoo
“If you forget to back up your costs during Bellman-Ford, your layovers will multiply faster than airline fees.”