Google · Question 4 · Graphs
Reverse Route to Get Itinerary
Problem
You are given a list of airline tickets where tickets[i] = [from, to]. Reconstruct the itinerary in order, using every ticket exactly once, starting from JFK.
Approach
Build the graph with destinations sorted in reverse, then run Hierholzer's walk: visit neighbours depth-first and prepend each airport when it runs out of edges.
Time O(ElogE)Space O(E)
How it works
- 1Build the adjacency lists with destinations sorted in reverse order.
- 2Walk depth-first from JFK, consuming each ticket once.
- 3Append an airport to the route when it has no unused tickets left.
- 4Reverse the collected route to get the forward 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; tickets[i].length == 2; all tickets belong to one valid itinerary starting at JFK.
Solution — read it, then walk it
Time O(ElogE)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