← Google bank

Google · Question 4 · Graphs

Reverse Route to Get Itinerary

GraphsPythoncode⏱ O(ElogE)💾 O(E)
Product-based

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

  1. 1Build the adjacency lists with destinations sorted in reverse order.
  2. 2Walk depth-first from JFK, consuming each ticket once.
  3. 3Append an airport to the route when it has no unused tickets left.
  4. 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.
↻ repeat↻ repeatyesnoSTARTfrom collections importdefaultdictDEFINEfind_itinerary(tickets)graph = defaultdict(list)for src, dst insorted(tickets,reverse=True)graph[src].append(dst)route = []DEFINE visit(airport)while graph[airport]visit(graph[airport].pop())route.append(airport)visit("JFK")RETURN route[::-1]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))tickets = [[next(it),next(it)] for _ inrange(n)]print(find_itinerary(tickets))if __name__ =="__main__"main()END
  • 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