Ctrl K

Lineup From Neighbor XORs

Medium
n runners stand in a line wearing the numbers 1 to n, each number exactly once, and n is odd. Instead of the numbers themselves, the judge wrote down an array neighbor_xors of length n - 1, where neighbor_xors[i] is the bitwise XOR of the numbers of runner i and runner i + 1. Restore the order of the runners. The answer is guaranteed to exist and to be unique.
Example 1
neighbor_xors=[2, 3] → [3, 1, 2]

The lineup [3, 1, 2]: 3 XOR 1 = 2 and 1 XOR 2 = 3.

Example 2
neighbor_xors=[7, 4, 5, 7] → [2, 5, 1, 4, 3]

The lineup [2, 5, 1, 4, 3]: 2 XOR 5 = 7, 5 XOR 1 = 4, 1 XOR 4 = 5, 4 XOR 3 = 7.

Example 3
neighbor_xors=[3, 6, 7, 4, 7, 6] → [4, 7, 1, 6, 2, 5, 3]

This is the lineup [4, 7, 1, 6, 2, 5, 3]: for instance, 4 XOR 7 = 3 and 5 XOR 3 = 6.

Constraints
  • 3 ≤ n < 10⁵, n is odd
  • len(neighbor_xors) = n - 1
  • neighbor_xors was built from some permutation of 1 to n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Topping Combo MediumAll Distinct Card Hands MediumThe Odd One Among Triples MediumTwo Values Without a Pair MediumSpot the Extra Copy Medium
loading Python…
Input
neighbor_xors=[2, 3]
Expected
[3, 1, 2]

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