A warehouse robot rearranges a row of n storage bins (each holding a distinct or repeated bin ID) using its onboard controller, which has no spare register to use as a temporary variable. It performs every swap with the classic three-step XOR trick:
a ^= b
b ^= a
a ^= b
The controller is given a sequence of q swap instructions, each naming two 0-indexed bin positions i and j (possibly i = j, meaning "swap a bin with itself" — a no-op that a careless XOR-trick implementation could corrupt to zero, since i = j means both names refer to the same physical register). Applying the trick to a register with itself must leave its value unchanged.
Apply all q instructions in order, then print the final row of bin IDs.
Line 1: an integer n.
Line 2: n space-separated integers, the initial bin IDs.
Line 3: an integer q.
Next q lines: two integers i j (0-indexed positions to swap), one pair per line.
n space-separated integers: the bin IDs after all q swaps, in final left-to-right order.
Example 1
Input
4 10 20 30 40 2 0 3 1 1
Expected
40 20 30 10
Explanation
Swapping positions 0 and 3 gives [40,20,30,10]; swapping position 1 with itself must leave the array unchanged, so the final array is 40 20 30 10.
Example 2
Input
3 5 5 9 1 0 1
Expected
5 5 9
Explanation
Positions 0 and 1 both hold 5, so swapping them leaves the array 5 5 9 unchanged.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →