Minimum-Cost Flight Path with Departure Window
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests constrained graph search: find the cheapest multi-leg flight route where only the first leg must depart within a given date range, connections must respect time ordering, and cycles are forbidden.
Minimum-Cost Flight Path with Departure Window
You are given a list of flights and must find the lowest-cost route from a starting airport to a target airport. Each flight is described by a list with six fields:
[flight_id, from_airport, to_airport, departure_time, arrival_time, price]
flight_id— a unique string identifier for the flightfrom_airport/to_airport— airport codes (strings)departure_time/arrival_time— ISO-8601 datetime strings, e.g."2024-01-15T09:30"price— a non-negative integer
Task
Return the minimum total price to travel from origin to destination, along with the ordered sequence of flight IDs that form that route.
The first leg of the route must have a departure_time that falls within the inclusive range [window_start, window_end]. Subsequent legs have no date restriction.
A valid connection between two consecutive flights requires that the second flight departs at or after the first flight arrives (same-minute connections are allowed).
No flight may appear more than once in a route.
Return value
- If
originequalsdestination, return[0, []]. - If a valid route exists, return
[total_price, [flight_id_1, flight_id_2, ...]]where the flight IDs are listed in travel order. - If no valid route exists, return
-1.
When multiple routes share the same minimum price, return the one whose flight ID list is lexicographically smallest.
How date/time comparisons work
All datetime and date strings are ISO-8601. Because ISO-8601 strings sort correctly as plain strings, you may compare them with the standard <, <=, >=, > operators. A date-only boundary like "2024-01-05" sorts before "2024-01-05T00:00", so a departure of "2024-01-05T10:00" would fall outside a window whose window_end is "2024-01-05".
Constraints
0 <= len(flights) <= 500- All
pricevalues are non-negative integers. departure_time < arrival_timefor every flight (no zero-duration flights in the input).- All datetime strings are valid ISO-8601 format and are comparable as plain strings.
- Flight IDs are unique across the entire input list.
- Airport codes are non-empty strings; there is no fixed alphabet.
window_start <= window_end
Examples
Example 1
Input: cheapest_flight_path([['F1', 'A', 'B', '2024-01-01T08:00', '2024-01-01T10:00', 100], ['F2', 'B', 'D', '2024-01-01T11:00', '2024-01-01T13:00', 80], ['F3', 'A', 'D', '2024-01-01T09:00', '2024-01-01T12:00', 250]], 'A', 'D', '2024-01-01T00:00', '2024-01-02T00:00')
Output: [180, ['F1', 'F2']]
Example 2
Input: cheapest_flight_path([['A1', 'NYC', 'CHI', '2024-02-10T07:00', '2024-02-10T09:00', 120], ['A2', 'CHI', 'LAX', '2024-02-10T09:00', '2024-02-10T12:00', 100], ['A3', 'NYC', 'LAX', '2024-02-10T08:00', '2024-02-10T12:00', 250]], 'NYC', 'LAX', '2024-02-10T00:00', '2024-02-10T23:59')
Output: [220, ['A1', 'A2']]
Example 3
Input: cheapest_flight_path([['X1', 'A', 'B', '2024-03-02T10:00', '2024-03-02T11:00', 10], ['X2', 'B', 'C', '2024-03-02T12:00', '2024-03-02T13:00', 10]], 'A', 'C', '2024-03-03T00:00', '2024-03-04T00:00')
Output: -1
Hints
Hint 1
Instead of treating airports as the nodes in your search, consider making each individual flight a node. Two paths reaching the same airport can have different onward options depending on when they land there — flight-level state captures this.
Hint 2
Dijkstra's algorithm works here because all prices are non-negative. Store (total_cost, path_tuple, flight_index) in a min-heap. The path tuple in the key gives you a free lexicographic tie-break with no extra bookkeeping.
Hint 3
ISO-8601 strings compare correctly with plain Python string operators, so you don't need to parse dates. Use that for both the departure-window check on the first leg and the arrival/departure ordering check on every connection.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model flights, not airports, as nodes
The key insight is that two paths reaching the same airport at different times have different options going forward. Modelling airports as nodes loses arrival-time information. Modelling each individual flight as a node preserves it: the node captures both "where you land" and "when you land", which together determine every valid onward connection.
Graph structure
- A directed edge exists from flight A to flight B when
B.from_airport == A.to_airportandB.departure_time >= A.arrival_time(same-minute connections are valid). - Edge weight is
B.price. - Valid start nodes are flights departing from
originwhosedeparture_timefalls in[window_start, window_end]. - A goal node is any flight whose
to_airport == destination.
Algorithm: Dijkstra with lazy deletion
Because all prices are non-negative, Dijkstra's algorithm finds the cheapest path. A min-heap stores tuples of (cumulative_cost, path_tuple, flight_index).
Including the full path tuple as the second element of the heap key gives lexicographic tie-breaking for free: when two routes have equal cost, Python's tuple comparison walks the ID sequences character by character and picks the smaller one — exactly the required behaviour.
Lazy deletion keeps the implementation simple: when a better route to a flight is discovered, a new entry is pushed without removing the old one. On pop, stale entries (whose cost/path no longer match the recorded best) are discarded immediately.
Time ordering and cycle prevention
- Time ordering is enforced by the
departure >= arrivalcheck on every candidate connection. Because ISO-8601 strings sort lexicographically in chronological order, plain string comparison is sufficient — no date parsing needed. - Cycles are prevented by the
if nxt_id in pathcheck. With non-negative prices an optimal route never needs to repeat a flight anyway, so this rule costs nothing in optimality while guaranteeing termination.
Correctness
Dijkstra pops nodes in non-decreasing order of (cost, path). The first time a node whose to_airport == destination is popped, no unexplored path can be cheaper (or lexicographically smaller at the same cost). Any such path would require a heap entry with a key no larger than the popped one, meaning it would have been popped first.
Edge cases
origin == destinationreturns[0, []]immediately.- No first-leg flight within the date window returns
-1. - A date-only
window_endlike"2024-01-05"sorts before"2024-01-05T00:00", so any departure on that day is excluded — consistent with plain string comparison. - Zero-price flights are handled correctly; the no-repeat rule prevents infinite zero-cost loops.
Complexity
Let F = number of flights, E = number of valid connection pairs (≤ F²), L = maximum route length (≤ F).
- Time:
O(E · (L + log E))— each edge expansion does anO(L)membership test and anO(log E)heap operation. In practice itineraries are short, reducing this to roughlyO(E log E). - Space:
O(F · L)for stored best paths,O(E · L)for heap entries in the worst case.
If tie-breaking were not required, parent pointers could replace full path tuples, dropping the L factor entirely.
import heapq
from collections import defaultdict
from typing import List
def cheapest_flight_path(
flights: List[List],
origin: str,
destination: str,
window_start: str,
window_end: str,
) -> object:
# A traveller who is already at the destination needs no flights.
if origin == destination:
return [0, []]
# Pre-build an index: airport -> list of flight indices departing from it.
# ISO-8601 strings sort lexicographically in chronological order, so all
# time comparisons below use plain string operators.
outgoing = defaultdict(list)
for idx, flight in enumerate(flights):
_, from_ap, _, _, _, _ = flight
outgoing[from_ap].append(idx)
# Dijkstra over flight-level states.
# Heap entry: (cumulative_cost, path_tuple_of_ids, flight_index)
# Storing the full path tuple in the key gives a free lexicographic
# tie-break: equal-cost entries are ordered by their ID sequence.
best_cost = {} # flight_index -> best cost seen so far
best_path = {} # flight_index -> corresponding path tuple
heap = []
# Seed the heap with every first leg that departs within the window.
for idx, flight in enumerate(flights):
fid, from_ap, _, departure, _, price = flight
if from_ap != origin:
continue
if not (window_start <= departure <= window_end):
continue
path = (fid,)
if idx not in best_cost or (price, path) < (best_cost[idx], best_path[idx]):
best_cost[idx] = price
best_path[idx] = path
heapq.heappush(heap, (price, path, idx))
while heap:
cost, path, idx = heapq.heappop(heap)
# Skip stale heap entries (lazy deletion).
if cost != best_cost.get(idx) or path != best_path.get(idx):
continue
_, _, to_ap, _, arrival, _ = flights[idx]
# First time we pop a flight landing at the destination, that is the
# cheapest route (Dijkstra pops in non-decreasing cost order).
if to_ap == destination:
return [cost, list(path)]
# Expand: try every flight that departs from the current landing airport.
for nxt_idx in outgoing.get(to_ap, ()):
nxt_id, _, _, departure, _, price = flights[nxt_idx]
# Connection must depart at or after the current flight lands.
if departure < arrival:
continue
# Disallow reusing a flight (prevents cycles; also sound for
# optimality because prices are non-negative).
if nxt_id in path:
continue
nxt_cost = cost + price
nxt_path = path + (nxt_id,)
if (nxt_idx not in best_cost or
(nxt_cost, nxt_path) < (best_cost[nxt_idx], best_path[nxt_idx])):
best_cost[nxt_idx] = nxt_cost
best_path[nxt_idx] = nxt_path
heapq.heappush(heap, (nxt_cost, nxt_path, nxt_idx))
return -1