Advertisement

Swapping Nodes in a Linked List - LeetCode 1721 Solution

Swapping Nodes in a Linked List - Complete Solution Guide

Swapping Nodes in a Linked List is LeetCode problem 1721, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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 k th node from the beginning and the k th node from the end (the list is 1-indexed ). Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] Example 2: Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5 Output: [7,9,6,6,8,7,3,0,9,5] Constraints: The number of nodes in the list is n . 1 <= k <= n <= 10 5 0 <= Node.val <= 100

Detailed Explanation

The problem asks us to swap the values of the k-th node from the beginning of a linked list with the k-th node from the end of the same linked list. The linked list is 1-indexed, meaning the first node is at index 1. The input is the head of the linked list and an integer k. The output is the head of the modified linked list after the swap.

Solution Approach

The solution utilizes a two-pointer approach to efficiently find both nodes to be swapped. First, it finds the k-th node from the beginning. Then, it uses two pointers, one starting from the head and the other starting from the k-th node from the beginning. By advancing both pointers until the second pointer reaches the end of the list, the first pointer will be pointing to the k-th node from the end. Finally, the values of the two nodes are swapped.

Step-by-Step Algorithm

  1. Step 1: Initialize a pointer 'right' to the head of the linked list.
  2. Step 2: Move the 'right' pointer 'k-1' steps forward to locate the k-th node from the beginning. Store this node in 'node1'.
  3. Step 3: Initialize a pointer 'left' to the head of the linked list.
  4. Step 4: Move both 'left' and 'right' pointers forward simultaneously until the 'right' pointer reaches the last node of the list (right.next == NULL).
  5. Step 5: At this point, the 'left' pointer will be pointing to the k-th node from the end of the list. Store this node in 'node2'.
  6. Step 6: Swap the values of 'node1' and 'node2'.
  7. Step 7: Return the head of the linked list.

Key Insights

  • Insight 1: We need to find both the k-th node from the beginning and the k-th node from the end without knowing the list's length beforehand.
  • Insight 2: A two-pointer technique can efficiently find the k-th node from the end in a single pass after finding the k-th node from the beginning.
  • Insight 3: We only need to swap the *values* of the nodes, not the nodes themselves, which simplifies the process.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Linked List, Two Pointers.

Companies

Asked at: Nvidia, Snowflake.