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 PairsInput (Disconnected):[5,1][4,5][11,9][9,4]⬇ Rearrange to form chain ⬇Output (Connected):[11,9][9,4][4,5][5,1]Valid Chain: 11→9→4→5→1Each pair's end = next pair's start
Understanding the Visualization
1
Input Pairs
Given disconnected pairs that need to be arranged
2
Find Chain
Arrange so each pair's end equals next pair's start
3
Valid Output
Connected chain where all pairs link together
Key Takeaway
🎯 Key Insight: Model as Eulerian path problem - traverse all edges exactly once in a directed graph
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