← Google bank

Google · Question 72 · Graphs

Reconstruct Itinerary

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

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

  1. 1Sort tickets in reverse so the smallest pops last.
  2. 2Walk depth-first from JFK, consuming each ticket.
  3. 3Append an airport when it has no tickets left.
  4. 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.
↻ repeat↻ repeatyesnoSTARTfrom collections importdefaultdictDEFINEfindItinerary(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(findItinerary(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