Skip to content

Python interview practice/Microsoft

Swap Nodes in Pairs

Mediumlinked-list · recursion

The problem

Given a linked list, swap every two adjacent nodes and return its head.

Function: def swapPairs(head):

Example input (a JSON list of arguments): [[1, 2, 3, 4]]
Expected output: [2, 1, 4, 3]

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Keep a predecessor pointer before each pair and reconnect the two nodes in reversed order.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def swapPairs(head):
    dummy=ListNode(0,head);prev=dummy
    while prev.next and prev.next.next:
        a=prev.next;b=a.next;a.next=b.next;b.next=a;prev.next=b;prev=a
    return dummy.next

Why it works

Keep a predecessor pointer before each pair and reconnect the two nodes in reversed order. Advance to the original first node after swapping. Values are not exchanged; the links are.

Complexity: O(n) time / O(1) extra space.

Time: O(n) time · Space: O(1) extra space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Microsoft.

See access and price

More free Microsoft questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.