Swap Nodes in Pairs — LeetCode 24 Python Solution

MediumRecursionLinked List
Problem
#24
Reading time
2 min

The problem

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.)

This statement is abridged. Read the full problem on LeetCode.

Python solution

Python
# 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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 24. Swap Nodes in Pairs is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Linked List.

The linked list guide has the Python template for the pattern and the 75 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 24. Swap Nodes in Pairs?
LeetCode 24. Swap Nodes in Pairs is rated Medium on LeetCode.
What is the time complexity of LeetCode 24. Swap Nodes in Pairs?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 24. Swap Nodes in Pairs?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 24. Swap Nodes in Pairs cover?
LeetCode 24. Swap Nodes in Pairs is tagged Recursion and Linked List on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview