AlgoMaster Logo

Reconstruct Itinerary

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Hierholzer’s Algorithm with DFS (Backtracking)

Hierholzer’s algorithm is a method to find an Eulerian path or cycle (a path or cycle that visits every edge exactly once) in a graph. Since the given problem is about reconstructing an itinerary that visits all flights (edges) exactly once, and starts from "JFK", we can use this approach directly.

The idea behind Hierholzer’s algorithm in this context is:

  • Start from "JFK" and greedily visit the lexicographically smallest destination city, marking that flight as "used".
  • Use Depth-First Search (DFS) to explore each destination and backtrack when there are no further cities to visit from the current city.
  • Append the current city to a route list when you can no longer move forward (i.e., dead-end).

Steps:

  1. Use a priority queue (a min-heap) to keep the adjacency list for each airport. This ensures the lexicographical order in flight selection.
  2. Perform a DFS recursively to explore the itinerary starting from "JFK".
  3. Append the current airport to the itinerary only when a dead-end is reached and all flights are utilized from the current airport.
  4. Reverse the itinerary at the end to get the correct order.

Code:

2. Hierholzer’s Algorithm with Iterative DFS (Using Stack)

Instead of performing the DFS recursively, this approach uses a stack to iteratively perform DFS. The principle remains the same—ensure all edges are visited exactly once, storing the itinerary in a reverse manner and then reversing it at the end.

Steps:

  1. Utilize a stack to simulate the DFS process.
  2. Start with pushing "JFK" onto the stack.
  3. While there are nodes to explore until the stack is empty:
    • Look at the top of the stack to get the current airport.
    • If there are outgoing flights from this airport, move to the lexicographically smallest airport using that flight.
    • If no flights left, add this airport to the route and pop from the stack.
  4. Reverse the itinerary list to construct the final itinerary correctly.

Code: