↓Skip to main content
  1. LeetCode/

LeetCode 24: Swap Nodes in Pairs

·2 mins· ·
LeetCode Medium Linked-List Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-21

  • Submissions: Time Limit Exceeded → Wrong Answer ×3 → Accepted → Runtime Error → Wrong Answer ×2 → Accepted ×2 → Runtime Error ×3 → Accepted ×2

Approach
#

Each step handles the two nodes after prev, a and b (Linked List Template 5):

  • prev.next becomes b
  • a.next becomes b’s old next
  • b.next becomes a

Then prev moves to a (now second in the pair). A dummy handles the head being swapped in the first pair.

My Attempts
#

This took 15 submissions in 2022:

  • TLE / WA: I first tried swapping in one line with node.val, node.next, node.next.next = ..., but targets are assigned left to right, so after node.next changed, node.next.next pointed at the wrong node, creating loops or dropping nodes; attempt 1 also never advanced node (TLE), and attempt 2 returned the final node (None) instead of the head, so [4] returned an empty list and [2, 2] kept only one node.
  • RE: reading head.next on an empty list.
  • Switching to a dummy with separate a and b variables passed.

Solution
#

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0, head)
        prev = dummy
        while prev.next and prev.next.next:
            a, b = prev.next, prev.next.next
            prev.next, a.next, b.next = b, b.next, a
            prev = a
        return dummy.next

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Python’s multiple assignment evaluates the whole right side first, so b.next is the old value; but targets are assigned left to right, so in node.next, node.next.next = ... the second target uses the already-updated node.next.

Interview Explanation
#

With a dummy, each step takes the next two nodes: the previous pair’s tail points at b, a points at b’s old next, b points at a, then move on two. Time O(n).

Related

LeetCode 2: Add Two Numbers
·2 mins
LeetCode Medium Linked-List Math Recursion
LeetCode 2 note: digits are stored in reverse, so add from the head digit by digit with a carry, looping until both lists end and no carry remains
LeetCode 19: Remove Nth Node From End of List
·2 mins
LeetCode Medium Linked-List Two-Pointers
LeetCode 19 note: from a dummy, move fast n + 1 steps ahead, then move both to the end; slow stops before the node to delete
LeetCode 234: Palindrome Linked List
·2 mins
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 note: find the middle with fast and slow pointers, reverse the second half, and compare from both ends with O(1) extra space
LeetCode 203: Remove Linked List Elements
·2 mins
LeetCode Easy Linked-List Recursion
LeetCode 203 note: the head may be deleted too, so a dummy head turns every deletion into deleting cur.next; do not advance after deleting
LeetCode 206: Reverse Linked List
·1 min
LeetCode Easy Linked-List Recursion
LeetCode 206 note: three pointers prev / cur / nxt; save the next node, then point cur.next back at prev
LeetCode 237: Delete Node in a Linked List
·1 min
LeetCode Medium Linked-List
LeetCode 237 note: without the previous node, copy the next node’s value over and delete the next node instead