Program to find airports in correct order in Python?

Finding airports in correct order from a shuffled list of flights is a classic graph traversal problem. We need to reconstruct the travel itinerary by finding an Eulerian path through the flight connections, ensuring lexicographical ordering when multiple valid paths exist.

Algorithm Overview

The solution uses Hierholzer's algorithm to find an Eulerian path in a directed graph ?

  • Build adjacency list from flight pairs
  • Track in-degree and out-degree for each airport
  • Find starting airport (out-degree - in-degree = 1, or lexicographically smallest)
  • Use DFS to traverse and build the path
  • Return reversed path for correct order

Implementation

from collections import defaultdict

class Solution:
    def solve(self, flights):
        # Track in-degrees, out-degrees, and adjacency list
        ins = defaultdict(int)
        outs = defaultdict(int)
        adj_list = defaultdict(list)
        
        # Build graph from flights
        for start, end in flights:
            adj_list[start].append(end)
            outs[start] += 1
            ins[end] += 1
        
        # Sort adjacency lists for lexicographical order
        for destinations in adj_list.values():
            destinations.sort()
        
        # Find starting airport
        start_airport = None
        end_airport = None
        
        for airport in adj_list.keys():
            degree_diff = outs[airport] - ins[airport]
            if degree_diff == 1:
                if start_airport:
                    return []  # Invalid: multiple starting points
                start_airport = airport
            elif degree_diff == -1:
                if end_airport:
                    return []  # Invalid: multiple ending points
                end_airport = airport
            elif degree_diff != 0:
                return []  # Invalid: unbalanced degrees
        
        # If no specific start found, use lexicographically smallest
        start_airport = start_airport if start_airport else min(adj_list.keys())
        
        # DFS to find Eulerian path
        path = []
        
        def dfs(airport):
            while outs[airport] > 0:
                # Get next unvisited destination
                next_index = len(adj_list[airport]) - outs[airport]
                outs[airport] -= 1
                dfs(adj_list[airport][next_index])
            path.append(airport)
        
        dfs(start_airport)
        return path[::-1]  # Reverse for correct order

# Test the solution
solution = Solution()
flights = [
    ["Mumbai", "Kolkata"],
    ["Delhi", "Mumbai"],
    ["Kolkata", "Delhi"]
]

result = solution.solve(flights)
print("Flight itinerary:", result)

The output of the above code is ?

Flight itinerary: ['Delhi', 'Mumbai', 'Kolkata', 'Delhi']

How It Works

The algorithm works by treating airports as nodes and flights as directed edges ?

  1. Graph Construction: Build adjacency list where each airport points to its destinations
  2. Degree Analysis: Calculate in-degree and out-degree for each airport
  3. Path Validation: Ensure at most one start (out > in by 1) and one end (in > out by 1)
  4. DFS Traversal: Use depth-first search to consume all flights
  5. Path Reconstruction: Reverse the collected path to get correct order

Example with Different Input

# Example with multiple valid paths - returns lexicographically smallest
flights2 = [
    ["JFK", "ATL"],
    ["ATL", "JFK"],
    ["JFK", "SFO"]
]

solution = Solution()
result2 = solution.solve(flights2)
print("Multiple paths example:", result2)
Multiple paths example: ['JFK', 'ATL', 'JFK', 'SFO']

Conclusion

This solution efficiently reconstructs flight itineraries using Eulerian path algorithms. The key insight is treating the problem as finding a path that visits every edge exactly once in a directed graph.

Updated on: 2026-03-25T12:18:03+05:30

421 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements