Valid Arrangement of Pairs - Problem

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 of pairs.

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

Input & Output

Example 1 — Basic Chain
$ Input: pairs = [[5,1],[4,5],[11,9],[9,4]]
Output: [[11,9],[9,4],[4,5],[5,1]]
💡 Note: Forms valid chain: 11→9→4→5→1 where each pair's end matches next pair's start (9=9, 4=4, 5=5)
Example 2 — Simple Path
$ Input: pairs = [[1,3],[3,2],[2,1]]
Output: [[1,3],[3,2],[2,1]]
💡 Note: Already in correct order: 1→3→2→1 forms complete cycle where 3=3 and 2=2
Example 3 — Two Pairs
$ Input: pairs = [[1,2],[2,3]]
Output: [[1,2],[2,3]]
💡 Note: Simple chain: 1→2→3 where first pair's end (2) equals second pair's start (2)

Constraints

  • 1 ≤ pairs.length ≤ 105
  • -106 ≤ starti, endi ≤ 106
  • starti ≠ endi
  • No duplicate pairs
  • There exists a valid arrangement of pairs

Visualization

Tap to expand
Valid Arrangement of Pairs INPUT Directed Graph from Pairs 11 9 4 5 1 pairs = [[5,1],[4,5], [11,9],[9,4]] 4 directed edges ALGORITHM STEPS 1 Build Adjacency List Map: start --> [end nodes] 2 Find Start Node Out-degree > In-degree (11) 3 DFS Traversal Visit edges, push to stack 4 Reverse Result Get valid arrangement DFS Path (Hierholzer) Visit: 11 --> 9 Visit: 9 --> 4 Visit: 4 --> 5 Visit: 5 --> 1 Stack: [5,1],[4,5],[9,4],[11,9] Reverse: [11,9]-->[9,4]... FINAL RESULT Valid Eulerian Path 11 --> 9 --> 4 5 --> 1 Verification [11,9]: end=9 [9,4]: start=9 [OK] [4,5]: start=4 [OK] [5,1]: start=5 [OK] Output [[11,9],[9,4], [4,5],[5,1]] [OK] Valid Path! Key Insight: This is an Eulerian Path problem! Pairs form directed edges in a graph. A valid arrangement exists when we can traverse each edge exactly once. Use Hierholzer's algorithm: find the start node (out-degree > in-degree), then DFS to build the path. Time: O(V+E), Space: O(V+E). TutorialsPoint - Valid Arrangement of Pairs | Eulerian Path (DFS)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen