You are given a list pairs where each pair [a, b] means that element a is immediately followed by element b in a circular sequence.
Reconstruct the circular sequence from these pairs. The input is guaranteed to form a valid Eulerian circuit: every element appears as the first value of a pair as many times as it appears as the second value, and all pairs form a single connected cycle.
Return the sequence as a list that starts from the smallest element and follows the circular order. The list should not repeat the starting element at the end.
Function Signature
def circular_sequence(pairs: list[list[int]]) -> list[int]:
Rules
-
Each pair is one step of the sequence and is used exactly once. If the same pair appears twice in the input, that step happens twice.
-
An element can appear more than once in the sequence. The returned list always has exactly
len(pairs)
elements.
-
The list starts with the smallest element. When more than one circular order uses every pair, return the lexicographically smallest list.
Constraints
-
1 <= len(pairs) <= 10^5
-
0 <= pairs[i][0], pairs[i][1] <= 10^5
-
The pairs form a valid Eulerian circuit.
-
All elements in the pairs form a single connected component.
Examples
Input: pairs = [[1,2],[2,3],[3,4],[4,1]]
Output: [1,2,3,4]
The pairs form one cycle, 1 -> 2 -> 3 -> 4 -> 1. Starting from the smallest element, 1, and leaving off the closing 1 gives [1,2,3,4].
Input: pairs = [[3,1],[1,2],[2,3],[3,4],[4,5],[5,3]]
Output: [1,2,3,4,5,3]
The circuit visits 3 twice: 1 -> 2 -> 3 -> 4 -> 5 -> 3 -> 1. Going from the first 3 straight back to 1 would end the loop with [3,4], [4,5] and [5,3] still unused, so this is the only order that uses all six pairs.
Input: pairs = [[1,2],[2,1],[1,3],[3,1]]
Output: [1,2,1,3]
Element 1 has two outgoing pairs, so two orders use every pair: [1,2,1,3] and [1,3,1,2]. The tie rule picks the lexicographically smaller one.