Valid Arrangement of Pairs Problem
#2097
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2097.
You are given a 0-indexed 2D integer array pairs where pairs[i] = [start_i, end_i]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have end_(i-1) == start_i.
Return any valid arrangement of pairs.
Note: The inputs will be generated such that there exists a valid arrangement of pairs.
Example 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 end_(i-1) always equals start_i.
end_0 = 9 == 9 = start_1
end_1 = 4 == 4 = start_2
end_2 = 5 == 5 = start_3
Example 2:
Input: pairs = [[1,3],[3,2],[2,1]]
Output: [[1,3],[3,2],[2,1]]
Explanation:
This is a valid arrangement since end_(i-1) always equals start_i.
end_0 = 3 == 3 = start_1
end_1 = 2 == 2 = start_2
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 end_(i-1) always equals start_i.
end_0 = 2 == 2 = start_1
end_1 = 1 == 1 = start_2
Constraints:
1 <= pairs.length <= 10^5pairs[i].length == 20 <= start_i, end_i <= 10^9start_i != end_i- No two pairs are exactly the same.
- There exists a valid arrangement of
pairs.
Solution
Approach: Eulerian Path (Hierholzer's Algorithm)
Treat every number as a node and every pair [a, b] as a directed edge a -> b. A valid arrangement uses every edge exactly once, one after another, which is an Eulerian path, and the problem guarantees one exists.
- Build adjacency lists and the value
out - inof each node. If some node hasout - in = 1, the path must start there; otherwise (an Eulerian circuit) any node, such aspairs[0][0], works. - Run Hierholzer's algorithm iteratively: keep a stack, and repeatedly follow an unused outgoing edge from the node on top; when the top node has none left, pop it and append it to the path.
- The nodes come out in reverse order. Reverse them and turn each consecutive pair of nodes into a pair of the answer.
Complexity: Time O(n) and space O(n) for n pairs.
from collections import defaultdict
class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
g = defaultdict(list)
deg = defaultdict(int)
for x, y in pairs:
g[x].append(y)
deg[x] += 1
deg[y] -= 1
start = pairs[0][0]
for k, v in deg.items():
if v == 1:
start = k
break
# Hierholzer's algorithm, iterative
stack = [start]
path = []
while stack:
u = stack[-1]
if g[u]:
stack.append(g[u].pop())
else:
path.append(stack.pop())
path.reverse()
return [[path[i], path[i + 1]] for i in range(len(path) - 1)]