DSA Graphs

Reconstruct Itinerary

Hierholzer's algorithm — pop edges greedily in lexicographic order and append to the route on backtrack.

Hard
Time O(E log E) Space O(E)
LeetCode
3 min read
graph eulerian dfs priority-queue

Problem#

Given a list of airline tickets (directed edges between airports), reconstruct the itinerary starting at “JFK” that uses every ticket exactly once. If multiple valid itineraries exist, return the lexicographically smallest.

Examples#

  • tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]["JFK","MUC","LHR","SFO","SJC"]
  • tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]["JFK","ATL","JFK","SFO","ATL","SFO"]

Constraints#

  • 1 <= tickets.length <= 300.

Approach#

Hierholzer’s Eulerian path. Store destinations per node in a min-heap. DFS: while the current node has outgoing edges, pop the smallest destination and recurse. After exhausting outgoing edges, append the node to the route. Reverse the route at the end.

Solution#

Reconstruct Itinerary
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<>>> g;
for (auto& t : tickets) g[t[0]].push(t[1]);
vector<string> route;
function<void(const string&)> dfs = [&](const string& u) {
auto& pq = g[u];
while (!pq.empty()) {
string v = pq.top(); pq.pop();
dfs(v);
}
route.push_back(u);
};
dfs("JFK");
reverse(route.begin(), route.end());
return route;
}
};

Editorial#

Hierholzer’s algorithm builds an Eulerian path by walking until stuck, then splicing in detours. Reversed post-order produces the correct order. Using min-heaps for destinations enforces lexicographic minimality at each greedy choice — which works because every Eulerian circuit visits every edge exactly once regardless of pick order.

Complexity#

  • Time: O(E log E).
  • Space: O(E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.