Imagine you have a collection of paired connections that need to be arranged in a specific order to form a valid chain. Each pair has a start point and an end point, and the challenge is to arrange them so that one pair's end connects perfectly with the next pair's start.
You are given a 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.
Goal: Return any valid arrangement of the given pairs that forms a continuous chain.
Example: If you have pairs [[5,1],[4,5],[11,9],[9,4]], one valid arrangement could be [[11,9],[9,4],[4,5],[5,1]] because 11→9→4→5→1 forms a continuous path.
The problem guarantees that a valid arrangement always exists, making this a classic Eulerian Path problem in graph theory!
Input & Output
Visualization
Time & Space Complexity
O(n!) to generate all permutations and O(n) to validate each permutation
Space for storing the current permutation and recursion stack
Constraints
- 1 ≤ pairs.length ≤ 105
- pairs[i].length == 2
- 0 ≤ starti, endi ≤ 109
- starti ≠ endi
- No two pairs are identical
- There exists a valid arrangement of pairs