Given airline tickets [from, to], reconstruct the itinerary in order, starting at JFK and using every ticket exactly once. If several itineraries exist, return the lexically smallest.
The itinerary is an Eulerian path. Greedily follow the smallest unused ticket; when an airport has no tickets left, add it to the route. The route comes out reversed, and dead-end detours are naturally placed at the end.
1function findItinerary(tickets: string[][]): string[] {2const adj = new Map<string, string[]>();3for (const [a, b] of [...tickets].sort().reverse()) (adj.get(a) ?? adj.set(a, []).get(a)!).push(b);4const route: string[] = [];5const visit = (a: string) => {6const dests = adj.get(a) ?? [];7while (dests.length) visit(dests.pop()!);8route.push(a);9};10visit("JFK");11return route.reverse();12}
Group tickets by departure.
Space: play/pause · ←/→: step