Reconstruct Itinerary

Algorithms
Hard
Stripe
54.1K views

Given a list of flight tickets, reconstruct the itinerary in order. The itinerary must begin with 'JFK'. If there are multiple valid itineraries, you should return the one that has the smallest lexical order. Use DFS and sorting.

Why Interviewers Ask This

Stripe evaluates candidates on graph traversal and state management under constraints. This question tests the ability to model real-world flight data as a directed graph, handle complex backtracking logic when dead-ends occur, and implement Hierholzer's algorithm efficiently. It specifically assesses lexical ordering requirements and the candidate's proficiency with DFS in non-trivial scenarios.

How to Answer This Question

1. Clarify constraints: Confirm if all tickets form a single valid Eulerian path starting at JFK and verify edge cases like multiple tickets to the same destination. 2. Model the Graph: Explain that you will use an adjacency list (HashMap) where keys are airports and values are sorted lists of destinations to ensure lexical order is met naturally during traversal. 3. Implement DFS Strategy: Describe using a post-order traversal approach. Instead of returning immediately upon visiting a node, recursively visit neighbors first. Only add the current airport to the result stack after all its outgoing edges are exhausted. 4. Handle Backtracking Logic: Emphasize that this specific DFS pattern automatically handles 'dead ends' by backtracking up the call stack until a valid path is found, ensuring the final reversed list represents the correct itinerary. 5. Optimize Complexity: Mention that sorting takes O(N log N) while the DFS runs in O(E), making the overall solution efficient for large datasets typical at Stripe.

Key Points to Cover

  • Explicitly mention using a HashMap with sorted lists for the adjacency structure
  • Demonstrate understanding of post-order DFS traversal for Eulerian path reconstruction
  • Explain how reversing the result stack yields the correct forward itinerary
  • Address the specific requirement of finding the lexicographically smallest path
  • Reference handling of disconnected components or dead-end scenarios gracefully

Sample Answer

To solve the Reconstruct Itinerary problem, I would first treat the flight tickets as a directed graph where each ticket represents an edge from one airport to another. Since we need the lexicographically smallest itinerary, my initial step is to sort the destinations for every departure airport in ascending order before building the adjacency list. This ensures that when we explore neighbors, we always pick the smallest available option first. I would then employ a Depth-First Search (DFS) strategy using a post-order traversal. The core insight here is that we don't add an airport to our final itinerary immediately upon visiting it. Instead, we recursively visit all reachable destinations from the current airport. We only push the current airport onto our result stack once we have exhausted all possible paths from it. This effectively handles the backtracking required when a path leads to a dead end; the algorithm naturally unwinds the stack, placing airports in the correct reverse order. Finally, since our construction adds nodes in reverse order of completion, I would reverse the resulting stack to produce the final itinerary starting from JFK. For example, given tickets [['JFK', 'SFO'], ['JFK', 'ATL'], ['SFO', 'ATL']], we sort SFO's neighbors to get ['ATL']. We visit JFK, go to ATL, find no exits, add ATL. Backtrack to JFK, go to SFO, go to ATL, add ATL, then SFO, then JFK. Reversing gives us the correct sequence. This approach guarantees validity and meets the lexical constraint efficiently.

Common Mistakes to Avoid

  • Attempting standard pre-order DFS which fails to handle dead-ends and produces invalid itineraries
  • Forgetting to sort the destination lists, leading to incorrect lexical ordering results
  • Using recursion without managing the visited state properly, causing infinite loops or missed edges
  • Neglecting to reverse the final result stack, outputting the itinerary in reverse chronological order

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 57 Stripe questions