Swapping Nodes in a Linked List — LeetCode 1721 Python Solution

MediumLinked ListTwo Pointers
Problem
#1721
Reading time
3 min

The problem

You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Example

Input
head = [1,2,3,4,5], k = 2
Output
[1,4,3,2,5]

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 swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        fast = slow = head
        for _ in range(k - 1):
            fast = fast.next
        p = fast
        while fast.next:
            fast, slow = fast.next, slow.next
        q = slow
        p.val, q.val = q.val, p.val
        return head

Complexity

MeasureComplexity
TimeO(n), where n is the length of the linked list
SpaceO(1) auxiliary

Pattern: Linked List

Rewire pointers in place, with a dummy head and a saved next to keep it safe. LeetCode 1721. Swapping Nodes in a Linked List 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 1721. Swapping Nodes in a Linked List?
LeetCode 1721. Swapping Nodes in a Linked List is rated Medium on LeetCode.
What is the time complexity of LeetCode 1721. Swapping Nodes in a Linked List?
The Python solution on this page runs in O(n), where n is the length of the linked list.
What is the space complexity of LeetCode 1721. Swapping Nodes in a Linked List?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1721. Swapping Nodes in a Linked List cover?
LeetCode 1721. Swapping Nodes in a Linked List is tagged Linked List and Two Pointers 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