← Home

332. Reconstruct Itinerary

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
332

Let's make this one less mysterious. For 332. Reconstruct Itinerary, the solution in this repository is mainly a stack solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: stack.

The notes already sitting in the source point us in the right direction:

  • Graph, Eulerian path, not understand?
  • https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C%2B%2B

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, findItinerary.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Graph, Eulerian path, not understand?
02//https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C%2B%2B
03//Runtime: 88 ms, faster than 19.85% of C++ online submissions for Reconstruct Itinerary.
04//Memory Usage: 15 MB, less than 54.64% of C++ online submissions for Reconstruct Itinerary.
05class Solution {
06public:
07    unordered_map<string, multiset<string>> edges;
08    vector<string> route;
09    
10    void dfs(string cur){
11        while(!edges[cur].empty()){
12            string next = *edges[cur].begin();
13            edges[cur].erase(edges[cur].begin());
14            // cout << next << " ";
15            dfs(next);
16        }
17        /*
18        end node has odd degree,
19        so we will stuck at end node,
20        now we write it to the end of route
21        */
22        route.insert(route.begin(), cur);
23    }
24    
25    vector<string> findItinerary(vector<vector<string>>& tickets) {
26        for(vector<string>& ticket : tickets){
27            edges[ticket[0]].insert(ticket[1]);
28        }
29        /*
30        all nodes' degrees are even,
31        except for start node and end node
32        */
33        
34        dfs("JFK");
35        
36        return route;
37    }
38};
39
40//iterative, not understand?
41//https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C%2B%2B
42//Runtime: 88 ms, faster than 19.85% of C++ online submissions for Reconstruct Itinerary.
43//Memory Usage: 14.6 MB, less than 71.60% of C++ online submissions for Reconstruct Itinerary.
44class Solution {
45public:
46    vector<string> findItinerary(vector<vector<string>>& tickets) {
47        unordered_map<string, multiset<string>> edges;
48        
49        for(vector<string>& ticket : tickets){
50            edges[ticket[0]].insert(ticket[1]);
51        }
52        
53        vector<string> route;
54        stack<string> stk;
55        stk.push("JFK");
56        
57        while(!stk.empty()){
58            while(edges.find(stk.top()) != edges.end() && !edges[stk.top()].empty()){
59                string next = *edges[stk.top()].begin();
60                edges[stk.top()].erase(edges[stk.top()].begin());
61                stk.push(next);
62            }
63            route.insert(route.begin(), stk.top());
64            stk.pop();
65        }
66        
67        return route;
68    }
69};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.