Google · Question 72 · Graphs
Reconstruct Itinerary
Problem
Given airline tickets, reconstruct itinerary in lexical order starting from 'JFK'.
Approach
Hierholzer's algorithm for Eulerian path using DFS. from collections import defaultdict
Time O(E log E)Space O(E)
How it works
- 1Sort tickets in reverse so the smallest pops last.
- 2Walk depth-first from JFK, consuming each ticket.
- 3Append an airport when it has no tickets left.
- 4Reverse the route for the lexical itinerary.
Sample input / output
Input: 4 MUC LHR JFK MUC SFO SJC LHR SFO Output: ['JFK', 'MUC', 'LHR', 'SFO', 'SJC']
Constraints
1 <= tickets.length <= 3000; valid itinerary exists starting at JFK; use every ticket once.
Solution — read it, then walk it
Time O(E log E)Space O(E)Loops 2Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/22
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits