Problem Description
Given a list of pairs where each pair represents a directed edge between two nodes, arrange the pairs in such a way that for every consecutive pair in the resulting sequence, the end of the previous pair equals the start of the next. It is guaranteed that such an arrangement exists.
Key Insights
- Interpret each pair as a directed edge from start to end.
- The problem reduces to finding an Eulerian path (or circuit) in a directed graph.
- If a vertex exists with out-degree exactly one greater than in-degree, it should be the starting vertex; otherwise, any vertex can serve as a valid starting node.
- Hierholzer’s algorithm is ideal to reconstruct an Eulerian path by performing a modified DFS that “peels off” cycles and ensures all edges get used exactly once.
Space and Time Complexity
Time Complexity: O(N), where N is the number of pairs since every edge is visited exactly once. Space Complexity: O(N) for storing the graph and the recursion/stack space for DFS.
Solution
We first build a graph mapping each start node to a list of its end nodes. To efficiently obtain and remove edges, sort each list in reverse order so that we can “pop” from the end. Next, determine a valid starting node: if there is a vertex whose out-degree is exactly one more than its in-degree, start from there. Otherwise, we pick any vertex that exists in the graph.
Using Hierholzer’s algorithm, perform a DFS:
- While the current vertex has outgoing edges, pop the last edge (which is efficient thanks to our reverse-sorted order) and recursively visit the end node.
- Append the current vertex to the path once all its edges are visited.
- Finally, reverse the recorded path to obtain the Eulerian path.
This path will be a list of vertices. To convert it back into a list of pairs, form pairs from consecutive vertices. Since each pair is exactly the edge used in the Eulerian path and all pairs are unique, this fulfills the problem's requirements.