KatInterview

528. Swapping Nodes in a Linked List

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to swap the values of two specific nodes in a singly linked list. These nodes are the kth node from the beginning and the kth node from the end. The list is 1-indexed. The key challenge is to efficiently locate these two nodes. Since we only need to swap the values, we don't need to change the next pointers of the nodes, which simplifies the task.

Solution

Swapping Nodes in a Linked List in Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
from typing import Optional

class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head:
            return None

        fast = head
        # Move fast pointer k-1 steps to reach the k-th node from the beginning.
        # The list is 1-indexed. Constraints 1 <= k <= n ensure fast is not null.
        for _ in range(k - 1):
            fast = fast.next
        
        # node1 is the k-th node from the beginning.
        node1 = fast

        slow = head
        # Move fast to the end of the list. At the same time, move slow.
        # When fast reaches the end, slow will be at the k-th node from the end.
        while fast.next:
            fast = fast.next
            slow = slow.next

        # node2 is the k-th node from the end.
        node2 = slow
        
        # Swap the values of the two nodes.
        node1.val, node2.val = node2.val, node1.val
        
        return head

Swapping Nodes in a Linked List in Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapNodes(ListNode head, int k) {
        if (head == null) {
            return null;
        }

        ListNode fast = head;
        // Move fast pointer k-1 steps to reach the k-th node from the beginning.
        // The list is 1-indexed. Constraints 1 <= k <= n ensure fast is not null.
        for (int i = 0; i < k - 1; i++) {
            fast = fast.next;
        }

        // node1 is the k-th node from the beginning.
        ListNode node1 = fast;
        
        ListNode slow = head;
        // Move fast to the end of the list. At the same time, move slow.
        // When fast reaches the end, slow will be at the k-th node from the end.
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }

        // node2 is the k-th node from the end.
        ListNode node2 = slow;

        // Swap the values of the two nodes.
        int temp = node1.val;
        node1.val = node2.val;
        node2.val = temp;

        return head;
    }
}

Swapping Nodes in a Linked List in C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapNodes(ListNode* head, int k) {
        if (!head) {
            return nullptr;
        }

        ListNode* fast = head;
        // Move fast pointer k-1 steps to reach the k-th node from the beginning.
        // The list is 1-indexed. Constraints 1 <= k <= n ensure fast is not null.
        for (int i = 0; i < k - 1; ++i) {
            fast = fast->next;
        }

        // node1 is the k-th node from the beginning.
        ListNode* node1 = fast;
        
        ListNode* slow = head;
        // Move fast to the end of the list. At the same time, move slow.
        // When fast reaches the end, slow will be at the k-th node from the end.
        while (fast->next != nullptr) {
            fast = fast->next;
            slow = slow->next;
        }

        // node2 is the k-th node from the end.
        ListNode* node2 = slow;

        // Swap the values of the two nodes.
        std::swap(node1->val, node2->val);

        return head;
    }
};

Swapping Nodes in a Linked List in TypeScript

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function swapNodes(head: ListNode | null, k: number): ListNode | null {
    if (!head) {
        return null;
    }

    let fast: ListNode = head;
    // Move fast pointer k-1 steps to reach the k-th node from the beginning.
    // The list is 1-indexed. Constraints 1 <= k <= n ensure fast is not null.
    for (let i = 0; i < k - 1; i++) {
        fast = fast.next!;
    }

    // node1 is the k-th node from the beginning.
    const node1: ListNode = fast;
    
    let slow: ListNode = head;
    // Move fast to the end of the list. At the same time, move slow.
    // When fast reaches the end, slow will be at the k-th node from the end.
    while (fast.next) {
        fast = fast.next;
        slow = slow.next!;
    }

    // node2 is the k-th node from the end.
    const node2: ListNode = slow;

    // Swap the values of the two nodes.
    const temp = node1.val;
    node1.val = node2.val;
    node2.val = temp;

    return head;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.