n distinct integers, but the row itself is lost. Only the neighbor pairs survived: links holds n - 1 pairs, and each pair [a, b] means that a and b stood next to each other. Every two adjacent numbers of the row have exactly one pair, but the pairs are shuffled, and the two numbers inside a pair may come in either order.
Rebuild the row. It can be read in two directions, so here is the rule: the row starts with the end number that comes first when you read links straight through, the first pair left to right, then the second, and so on.links=[[7, 3], [5, 9], [3, 5]] → [7, 3, 5, 9]
The row is 7, 3, 5, 9 (or the reverse). Reading links in order, the first end number met is 7, so the row starts with it.
links=[[4, 8], [8, -2], [6, 4]] → [-2, 8, 4, 6]
The chain is -2 — 8 — 4 — 6. Both 4 and 8 are in the middle, and the first end met is -2 (in the second pair), so the answer is [-2, 8, 4, 6].
links=[[0, -5]] → [0, -5]
Two numbers and one pair; the first of them, 0, is an end.
len(links) = n − 1, each pair holds two numberslinks[i][j] ≤ 10⁵links=[[7, 3], [5, 9], [3, 5]]
[7, 3, 5, 9]
Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.