Leetcode #24: Swap Nodes in Pairs
In this guide, we solve Leetcode #24 Swap Nodes in Pairs in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) Example 1: Input: head = [1,2,3,4] Output: [2,1,4,3] Explanation: Example 2: Input: head = [] Output: [] Example 3: Input: head = [1] Output: [1] Example 4: Input: head = [1,2,3] Output: [2,1,3] Constraints: The number of nodes in the list is in the range [0, 100].
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Recursion, Linked List
Intuition
Linked list problems often require pointer manipulation rather than extra memory.
Two-pointer techniques expose cycles, midpoints, or reordering patterns.
Approach
Traverse with fast/slow pointers or reverse sublists when needed.
Maintain invariants carefully to avoid losing nodes.
Steps:
- Traverse with pointers.
- Reverse or split if required.
- Reconnect nodes correctly.
Python Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
t = self.swapPairs(head.next.next)
p = head.next
p.next = head
head.next = t
return p
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.