KatInterview

Build Travel Route from Airline Tickets

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsgraphsdfseulerian-path

Last updated

Tests directed graph traversal, Eulerian path construction, and lexicographical ordering with Hierholzer's algorithm.

You receive a collection of airline tickets, each represented as a pair [from_airport, to_airport] indicating a one-way flight. Your task is to assemble these tickets into a complete travel route that visits every flight exactly once.

The route must satisfy these requirements:

  1. Begin at airport "JFK".
  2. Use every ticket exactly once.
  3. When multiple valid routes exist, return the one that is lexicographically smallest when compared as a sequence of airport codes.

You may assume a valid route always exists.

Input:

  • tickets: a list of ticket pairs, where each ticket is [origin, destination] with both being 3-letter uppercase airport codes.

Output:

  • A list of airport codes representing the complete journey in order.

Constraints

  • 1 <= len(tickets) <= 10,000
  • Each ticket contains exactly two airport codes.
  • Airport codes are 3-letter uppercase strings.
  • A valid solution is guaranteed to exist.

Examples

Example 1

Input: build_route([['MUC', 'LHR'], ['JFK', 'MUC'], ['SFO', 'SJC'], ['LHR', 'SFO']])

Output: ['JFK', 'MUC', 'LHR', 'SFO', 'SJC']

Example 2

Input: build_route([['JFK', 'SFO'], ['JFK', 'ATL'], ['SFO', 'ATL'], ['ATL', 'JFK'], ['ATL', 'SFO']])

Output: ['JFK', 'ATL', 'JFK', 'SFO', 'ATL', 'SFO']

Hints

Hint 1

Model the tickets as directed edges in a graph where airports are nodes. You need to find a path that uses every edge exactly once.

Hint 2

When choosing between multiple destinations from the same airport, always prefer the lexicographically smallest option. However, a greedy approach alone will fail—consider what happens if the smallest choice leads to a dead end.

Hint 3

Hierholzer's algorithm solves this by using post-order traversal: when you reach an airport with no remaining outgoing flights, record it and backtrack. The final path emerges in reverse order.