Skip to Content
LeetCode The Hard Way
2000 - 2099

2097 - Valid Arrangement of Pairs (Hard)

https://leetcode.com/problems/valid-arrangement-of-pairs

Problem Statement

You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti.

Return any valid arrangement ofpairs.

Note: The inputs will be generated such that there exists a valid arrangement of pairs.

OriginalPython3Example 1:

Input: pairs = [[5,1],[4,5],[11,9],[9,4]]
Output: [[11,9],[9,4],[4,5],[5,1]]
Explanation:
This is a valid arrangement since endi-1 always equals starti.
end0 = 9 == 9 = start1 
end1 = 4 == 4 = start2
end2 = 5 == 5 = start3

Example 2:

Input: pairs = [[1,3],[3,2],[2,1]]
Output: [[1,3],[3,2],[2,1]]
Explanation:
This is a valid arrangement since endi-1 always equals starti.
end0 = 3 == 3 = start1
end1 = 2 == 2 = start2
The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.

Example 3:

Input: pairs = [[1,2],[1,3],[2,1]]
Output: [[1,2],[2,1],[1,3]]
Explanation:
This is a valid arrangement since endi-1 always equals starti.
end0 = 2 == 2 = start1
end1 = 1 == 1 = start2

Constraints:

  • 1 <= pairs.length <= 1e5
  • pairs[i].length == 2
  • 0 <= starti, endi <= 1e9
  • starti != endi
  • No two pairs are exactly the same.
  • There exists a valid arrangement of pairs.

Approach 1: Iterative Hierholzer's Algorithm for an Eulerian Trail

We can think of the input as a directed graph. Each number is a vertex, and each pair [u,v][u, v] is an edge going from uu to vv. For example, [5,1][5, 1] means we can move from vertex 55 to vertex 11. The goal is to order all these edges so that the destination of one edge is the starting point of the next edge.

A path that uses every edge exactly once is called an Eulerian trail. This is exactly what the problem asks us to find. A vertex can appear multiple times in the trail, but each input pair must be used only once. Since the problem guarantees that a valid arrangement exists, we do not need to check whether an Eulerian trail is possible.

First, we build adjadj, an adjacency list. Here, adj[u]adj[u] contains the destinations of all edges leaving uu. We also build degdeg, which stores the difference between the number of outgoing edges and incoming edges for each vertex. For every pair [u,v][u, v], we increase deg[u]deg[u] by one and decrease deg[v]deg[v] by one.

The value of degdeg helps us choose the correct starting vertex. Every time we enter an intermediate vertex, we must also leave it, so its incoming and outgoing edge counts must match. However, if the trail starts and ends at different vertices, the starting vertex needs one extra outgoing edge. Therefore, if a vertex has deg[u]==1deg[u] == 1, we must start there. Otherwise, the trail forms a circuit, and we can start at the first pair's starting vertex.

We use Hierholzer's algorithm, implemented with a stack named stst. Initially, the stack contains only the chosen starting vertex. The stack keeps track of the current route we are exploring. While the vertex on top of the stack has an unused outgoing edge, we remove one destination from its adjacency list using pop()pop() and push that destination onto the stack. Removing the edge ensures that it cannot be used again.

Eventually, the vertex on top of the stack will have no unused outgoing edges. At that point, we remove it from stst. If the stack is still nonempty, the new top is the vertex from which we reached the removed vertex, so we append that edge to resres. This is the backtracking part of the algorithm: whenever we cannot continue forward, we return to an earlier vertex and check whether it has more edges to explore.

Importantly, we record edges during backtracking, not when we first traverse them. Simply recording edges as we move forward could lead us to finish at a dead end while some edges remain unused elsewhere. Recording during backtracking allows the algorithm to combine those remaining routes into one valid trail. The edges are collected in reverse order, so we return in reverse.

For example, consider pairs=[[1,2],[1,3],[2,1]]pairs = [[1, 2], [1, 3], [2, 1]]. Vertex 11 has two outgoing edges and one incoming edge, so deg[1]==1deg[1] == 1 and we start there. Because pop()pop() removes the last destination, the algorithm first takes 1→31 → 3. Vertex 33 has no outgoing edges, so [1,3][1, 3] is added to resres. Back at vertex 11, the algorithm explores 1→2→11 → 2 → 1. During backtracking, it adds [2,1][2, 1] and then [1,2][1, 2]. Reversing resres produces [[1,2],[2,1],[1,3]][[1, 2], [2, 1], [1, 3]], which is a valid arrangement.

The time complexity is O(n)O(n) and the space complexity is O(n)O(n).

Written by@wkw
class Solution:
    def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
        res = []
        adj, deg = defaultdict(list), Counter()
        for u, v in pairs:
            adj[u].append(v)
            deg[u] += 1
            deg[v] -= 1
        st = [next((u for u in deg if deg[u] == 1), pairs[0][0])]
        while st:
            if adj[st[-1]]: st.append(adj[st[-1]].pop())
            else:
                v = st.pop()
                if st: res.append([st[-1], v])
        return res[::-1]

On this page