AlgoInsight

DSA problem

Valid Arrangement of Pairs

HardEulerian CircuitPattern: Eulerian Circuittop600AmazonGoogleMicrosoftBloombergMeta

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. The input is guaranteed to admit at least one valid arrangement.

This is an Eulerian path problem in disguise. Treat each pair [u, v] as a directed edge u -> v in a multigraph. A "valid arrangement" is precisely a sequence of edges in which each edge's tail equals the previous edge's head — i.e. an Eulerian path that uses every edge exactly once. Because the input is guaranteed to permit such an arrangement, an Eulerian path is guaranteed to exist in this graph.

The starting vertex matters. If there is some vertex s whose out-degree exceeds its in-degree by exactly one, the Eulerian path must begin at s; otherwise the graph has an Eulerian circuit and we may begin at any vertex with at least one outgoing edge (an arbitrary vertex from the first pair works). After fixing the start, the rest of the construction is Hierholzer's algorithm.

The optimal approach builds an adjacency map from u to a stack of outgoing destinations, computes in- and out-degrees, picks the correct start, and runs an iterative DFS that consumes edges and emits them in reverse post-order. Each emitted edge corresponds to a pair, so reversing the emission list yields a valid arrangement. The algorithm runs in O(V + E) time and space, where E = pairs.length.

Examples

Example 1
Input: pairs = [[5,1],[4,5],[11,9],[9,4]]
Output: [[11,9],[9,4],[4,5],[5,1]]
Explanation: The chain 11 -> 9 -> 4 -> 5 -> 1 uses every pair exactly once. Vertex 11 has out-degree 1 and in-degree 0, so it must be the start.
Example 2
Input: pairs = [[1,3],[3,2],[2,1]]
Output: [[1,3],[3,2],[2,1]]
Explanation: All vertices have equal in- and out-degree, so the graph has an Eulerian circuit; any starting vertex works and "1" from the first pair is a valid choice.
Example 3
Input: pairs = [[1,2],[1,3],[2,1]]
Output: [[1,2],[2,1],[1,3]]
Explanation: Vertex 1 has out-degree 2 and in-degree 1 (excess out-degree = 1), so the Eulerian path must start at 1 and end at 3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

grapheulerian-pathhierholzerdfs

Browse all DSA problems