HardDepth-First SearchGraphEulerian CircuitUpdated Sep 2026

2097. Valid Arrangement of Pairs

Asked at Goldman Sachs

Difficulty

Hard

Time

O(E)

Space

O(E)

Pattern

Depth-First Search

Companies

1

Problem

You are given a list of pairs, where each pair is [start, end]. You must reorder the pairs so that they chain together: the end of one pair must equal the start of the next pair. Return any valid ordering.

Think of each pair as a directed edge from start to end. A valid arrangement is a path that uses every edge exactly once. This is called an Eulerian path. The input is guaranteed to have at least one valid arrangement.

You do not need to find the only answer — any correct ordering is accepted. The numbers can be large (up to 10^9), so use a hash map for the graph, not an array.

Chain the pairs end to start

pairs[5,1][4,5][11,9][9,4]0123Reorder so that 9→9, 4→4 and 5→5 line up.chainone path[11,9][9,4][4,5][5,1]0123The result is a single path that uses every pairexactly once.
Each pair's end must equal the next pair's start, so the pairs form one unbroken chain.

Constraints

  • ●1 <= pairs.length <= 10^5
  • ●pairs[i].length == 2
  • ●0 <= start_i, end_i <= 10^9
  • ●start_i != end_i
  • ●No two pairs are exactly the same
  • ●There exists a valid arrangement of pairs

Examples

Example 1
Inputpairs = [[5,1],[4,5],[11,9],[9,4]]
Output[[11,9],[9,4],[4,5],[5,1]]
WhyThe chain works because 9 ends the first pair and starts the second, 4 ends the second and starts the third, and 5 ends the third and starts the fourth. Every pair is used exactly once.
Example 2
Inputpairs = [[1,3],[3,2],[2,1]]
Output[[1,3],[3,2],[2,1]]
WhyThis forms a cycle: 1→3, 3→2, 2→1. The end of each pair matches the start of the next, and the last pair's end (1) matches the first pair's start.
Example 3
Inputpairs = [[1,2],[1,3],[2,1]]
Output[[1,2],[2,1],[1,3]]
WhyPair 1→2 is followed by 2→1 (end 2 matches start 2), then 1→3 (end 1 matches start 1). All three pairs are used.

Asked At

1 companies
CompanyDifficulty
Goldman SachsHardView all Goldman Sachs questions →

How to Think About It

1

Model numbers as nodes and each pair as a directed edge start -> end. A valid arrangement is a path using every edge exactly once — an Eulerian path.

2

Where to start: if some node has out-degree - in-degree = 1, the path must start there. Otherwise every node is balanced (an Eulerian circuit), so start anywhere with outgoing edges.

3

Key insight (Hierholzer): walk edges greedily, removing each as you use it. When you reach a node with no unused edges, add it to the output and back up. The output, reversed, is the Eulerian path — detours get spliced in automatically.

4

Use an explicit stack instead of recursion; there can be 10^5 edges.

5

Convert the node sequence back into pairs: consecutive nodes (path[i], path[i+1]).

Optimal Approach

Step 1: Build adjacency lists and out - in degree differences.
Step 2: start = node with difference 1, or pairs[0][0] if none.
Step 3: Stack-based Hierholzer: push start; while the stack is not empty, if the top has unused edges, pop one edge and push its target; otherwise pop the top into path.
Step 4: Reverse path and return [[path[i], path[i+1]] ...].

Time: O(E). Space: O(E).

Hierholzer walks edges and backtracks

adjacency11→99→44→55→1Build a directed graph: each pair becomes an edgestart → end.stack119451← topPush nodes while edges remain; when the top has nounused edge, pop it into the path.path (reversed)node order11945101234Reversing the popped order gives the node sequence 11,9, 4, 5, 1.start = node with out − in = 1else start = pairs[0][0]answer = consecutive node pairs
We follow unused edges until stuck, then record nodes on the way back; reversing gives the Eulerian path.
ComplexityTime O(E)Space O(E)Each edge is pushed and popped once, so the work is linear in the number of pairs E; the adjacency map and the path both hold up to E entries.

What Trips People Up in Real Interviews

1

Trying backtracking over pair orders — exponential.

2

Starting at an arbitrary node when a node with extra out-degree exists; the walk then gets stuck with unused edges.

3

Appending nodes to the path when you enter them instead of when you leave them. Hierholzer's post-order is what splices detours correctly.

4

Recursing 10^5 deep in Python or Java. Use an explicit stack.

Solution Code

O(E) time
from collections import defaultdict

def validArrangement(pairs):
    adj = defaultdict(list)
    diff = defaultdict(int)
    for a, b in pairs:
        adj[a].append(b)
        diff[a] += 1
        diff[b] -= 1
    start = pairs[0][0]
    for node, d in diff.items():
        if d == 1:
            start = node
            break
    stack = [start]
    path = []
    while stack:
        u = stack[-1]
        if adj[u]:
            stack.append(adj[u].pop())
        else:
            path.append(stack.pop())
    path.reverse()
    return [[path[i], path[i + 1]] for i in range(len(path) - 1)]

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Valid Arrangement of Pairs problem?

Valid Arrangement of Pairs asks you to reorder pairs `[start, end]` so that each pair's end equals the next pair's start. Treat each pair as a directed edge — you need a path that uses every edge exactly once, which is an Eulerian path. Hierholzer's algorithm builds it in linear time.

How do you solve Valid Arrangement of Pairs?

The optimal approach runs in O(E) time and O(E) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Valid Arrangement of Pairs?

Valid Arrangement of Pairs is asked at Goldman Sachs. It is a hard difficulty problem.

What are common mistakes on Valid Arrangement of Pairs?
  • Trying backtracking over pair orders — exponential.
  • Starting at an arbitrary node when a node with extra out-degree exists; the walk then gets stuck with unused edges.
  • Appending nodes to the path when you enter them instead of when you leave them. Hierholzer's post-order is what splices detours correctly.
  • Recursing `10^5` deep in Python or Java. Use an explicit stack.