Ctrl K

Rebuild a Row From Neighbor Pairs

Medium
There was a row of 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.
Example 1
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.

Example 2
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].

Example 3
links=[[0, -5]] → [0, -5]

Two numbers and one pair; the first of them, 0, is an end.

Constraints
  • 2 ≤ n ≤ 10⁵
  • len(links) = n − 1, each pair holds two numbers
  • -10⁵ ≤ links[i][j] ≤ 10⁵
  • All numbers in the row are distinct, and the pairs really describe some row
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStop a Process Branch MediumPath Totals in a Coded Tree MediumMerge Contact Cards MediumChains of Synonyms MediumA Board Cut by Slashes Medium
loading Python…
Input
links=[[7, 3], [5, 9], [3, 5]]
Expected
[7, 3, 5, 9]

Run checks the first 3 tests in your browser. Submit checks all 78 tests on the server, hidden ones included.