Rebuild a Trip Itinerary From Unordered Flight Segments

Last updated: November 29, 2026

Quick Overview

Given unordered flight segments as (from, to) airport codes that together form one trip starting at 'JFK', reconstruct the itinerary that uses every segment exactly once, choosing the lexicographically smallest when several exist.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given unordered flight segments as (from, to) airport codes that together form one trip starting at 'JFK', reconstruct the itinerary that uses every segment exactly once, choosing the lexicographically smallest when several exist.

An Eulerian path problem in the style of Meta's onsite, framed around rebuilding a traveler's trip from booking fragments for a travel ad or Messenger trip card. The interviewer checks whether you see that greedy smallest-next-airport fails and that Hierholzer's algorithm with post-order insertion fixes it.

What the Interviewer Expects
  • Models segments as directed edges and the itinerary as an Eulerian path
  • Shows why picking the smallest next airport greedily can strand you
  • Uses Hierholzer's algorithm: append on dead end, reverse at the end
  • Sorts or heaps each adjacency list to get lexicographic order
  • Implements it iteratively
Key Topics to Cover
Eulerian path
Hierholzer's algorithm
DFS
Graphs
Heap
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How do you find the start airport if it is not given?
  • How would you detect that no valid itinerary exists?
  • What changes if segments are undirected?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: list of [from, to] segments. Output: list of airports of length segments + 1, starting at JFK. A valid itinerary is guaranteed. Up to 300 segments, duplicates allowed....

High-Level Design

Each segment is a directed edge to be used once, so the itinerary is an Eulerian path from JFK. Sort each airport's destinations in reverse so pop() returns the smallest. Walk with a stack: while th...


Submit Your Answer
Markdown supported