LeetCode 1721: Swapping Nodes in a Linked List Solution

Master LeetCode problem 1721 (Swapping Nodes in a Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1721. Swapping Nodes in a Linked List

Problem Explanation

Explanation

To swap the kth node from the beginning with the kth node from the end in a linked list, we can follow these steps:

  1. Traverse the linked list to find the kth node from the beginning and store its value.
  2. Traverse the linked list again to find the kth node from the end and swap its value with the previously stored value.
  3. Return the modified linked list.

Time complexity: O(n) where n is the number of nodes in the linked list. Space complexity: O(1)

Solution Code

class Solution {
    public ListNode swapNodes(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy, slow = dummy, first = dummy, second = dummy;
        
        // Move fast k nodes ahead
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        
        first = fast;
        
        // Move fast to the end and slow will reach kth node from the end
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        
        second = slow;
        
        // Swap values
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
        
        return head;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1721 (Swapping Nodes in a Linked List)?

This page provides optimized solutions for LeetCode problem 1721 (Swapping Nodes in a Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1721 (Swapping Nodes in a Linked List)?

The time complexity for LeetCode 1721 (Swapping Nodes in a Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1721 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1721 in Java, C++, or Python.

Back to LeetCode Solutions