327. Swap in Twos

A row of dominoes is stored as a chain: every domino carries a number and a link to the next one, and head is the first domino. A prankster walks along the row and exchanges neighbours two at a time: the first with the second, the third with the fourth, and so on.

Return the head of the chain after every adjacent pair has been exchanged. If the number of dominoes is odd, the last one has no partner and stays where it is. You must exchange the dominoes themselves by changing their links, not just copy numbers between them, although only the resulting order of values is checked. An empty chain is returned as it is.

Example 1

Input:
head = [11,22,33,44,55]
Output:
[22,11,44,33,55]
Explanation:

Pairs (11,22) and (33,44) are exchanged and 55 stays: 22, 11, 44, 33, 55.

Example 2

Input:
head = [6,1,9,3]
Output:
[1,6,3,9]
Explanation:

Both pairs are exchanged: 1, 6, 3, 9.

Constraints

0 ≤ chain length ≤ 105
-1000 ≤ node value ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…