#24

Swap Nodes in Pairs

Medium
Linked ListRecursionLinked ListTwo PointersRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Iterative)
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution involves swapping nodes directly in the linked list without using extra space for values. This is efficient because we only traverse the list once, modifying pointers directly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dummy node to handle edge cases and set it to point to the head.
  2. 2Step 2: Use a pointer to traverse the list in pairs.
  3. 3Step 3: For each pair, adjust the pointers to swap them.
solution.py20 lines
1# Full working Python code with comments
2class ListNode:
3    def __init__(self, val=0, next=None):
4        self.val = val
5        self.next = next
6
7def swapPairs(head):
8    dummy = ListNode(0)
9    dummy.next = head
10    prev = dummy
11    while prev.next and prev.next.next:
12        first = prev.next
13        second = first.next
14        # Swapping
15        first.next = second.next
16        second.next = first
17        prev.next = second
18        # Move to the next pair
19        prev = first
20    return dummy.next

Complexity note: The time complexity is O(n) because we traverse the list only once. The space complexity is O(1) since we are not using any additional data structures that grow with input size.

  • 1Recognizing that we can swap nodes directly instead of using values can significantly optimize the solution.
  • 2Understanding the role of a dummy node can help manage edge cases more effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.