332. Reconstruct Itinerary
Asked at 22Apple35Google34Amazon30Bloomberg25Microsoft12Meta12Pinterest100PhonePe64Netflix85Compass74Booking.com65Citadel64eBay64Yandex55Flipkart52Palo Alto Networks50Adobe44Uber44Walmart Labs43Visa39Salesforce35Capital One35
Problem
tickets[i] = [from, to] are airline tickets. Rebuild the itinerary that starts at "JFK" and uses every ticket exactly once. If several exist, return the one that is lexicographically smallest when read as a sequence of airport codes. At least one valid itinerary exists.
Example: [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] → ["JFK","MUC","LHR","SFO","SJC"]
Use every ticket exactly once = Eulerian path. Hierholzer: DFS taking the smallest destination first, append a node after all its edges are used, then reverse. Dead ends get placed at the end automatically.
JFK -> KUL (dead end) and JFK -> NRT -> JFK
DFS JFK: go KUL (smallest) -> stuck -> post-order [KUL]
back at JFK: go NRT -> JFK -> stuck ... -> [KUL, JFK, NRT, JFK]
reverse -> JFK NRT JFK KUL
Complexity: O(E log E).
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
g = defaultdict(list)
for a, b in sorted(tickets, reverse=True):
g[a].append(b) # reverse-sorted so pop() gives smallest
route, st = [], ["JFK"]
while st:
while g[st[-1]]:
st.append(g[st[-1]].pop())
route.append(st.pop())
return route[::-1]
T = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
assert Solution().findItinerary(T) == ["JFK", "MUC", "LHR", "SFO", "SJC"]
assert Solution().findItinerary([["JFK", "KUL"], ["JFK", "NRT"], ["NRT", "JFK"]]) == ["JFK", "NRT", "JFK", "KUL"]
class Solution {
public List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> g = new HashMap<>();
for (List<String> t : tickets) g.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).add(t.get(1));
LinkedList<String> route = new LinkedList<>();
Deque<String> st = new ArrayDeque<>(List.of("JFK"));
while (!st.isEmpty()) {
PriorityQueue<String> out = g.get(st.peek());
if (out != null && !out.isEmpty()) st.push(out.poll());
else route.addFirst(st.pop());
}
return route;
}
}
func findItinerary(tickets [][]string) []string {
g := map[string][]string{}
for _, t := range tickets {
g[t[0]] = append(g[t[0]], t[1])
}
for _, dests := range g {
sort.Sort(sort.Reverse(sort.StringSlice(dests))) // popping from the end gives the smallest
}
route, st := []string{}, []string{"JFK"}
for len(st) > 0 { // Hierholzer: an airport joins the route once it has no tickets left
top := st[len(st)-1]
if d := g[top]; len(d) > 0 {
g[top] = d[:len(d)-1]
st = append(st, d[len(d)-1])
} else {
route = append(route, top)
st = st[:len(st)-1]
}
}
for i, j := 0, len(route)-1; i < j; i, j = i+1, j-1 {
route[i], route[j] = route[j], route[i]
}
return route
}