02. Swap Kth Nodes from Ends
β GFG solution to swap kth nodes from beginning and end of a singly linked list: efficient pointer manipulation technique with optimal time complexity. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given the head of a singly linked list and an integer k
, swap the kth node (1-based index) from the beginning and the kth node from the end of the linked list. Return the head of the final formed list and if it's not possible to swap the nodes return the original list.
The task involves identifying two specific nodes based on their positions from opposite ends and performing a complete node swap while maintaining the integrity of the linked list structure.
π Examples
Example 1
Input: k = 1, List: 1 -> 2 -> 3 -> 4 -> 5
Output: 5 -> 2 -> 3 -> 4 -> 1
Explanation: Here k = 1, hence after swapping the 1st node from the beginning
and end the new list will be 5 -> 2 -> 3 -> 4 -> 1.
Example 2
Input: k = 2, List: 5 -> 7 -> 8 -> 5 -> 10 -> 3
Output: 5 -> 9 -> 8 -> 5 -> 10 -> 3
Explanation: Here k = 2, hence after swapping the 2nd node from the beginning
and end the new list will be 5 -> 9 -> 8 -> 5 -> 10 -> 3.
Example 3
Input: k = 3, List: 1 -> 2 -> 3 -> 4 -> 5 -> 6
Output: 1 -> 2 -> 4 -> 3 -> 5 -> 6
Explanation: Swapping 3rd node from start (3) with 3rd node from end (4).
π Constraints
$1 \le \text{list size} \le 10^4$
$1 \le \text{node->data} \le 10^6$
$1 \le k \le 10^4$
β
My Approach
The optimal approach uses Two-Pointer Technique with careful pointer manipulation to efficiently locate and swap the target nodes:
Optimized Single Pass Algorithm
Length Calculation:
Traverse the entire list once to determine the total number of nodes
n
.Handle edge cases: empty list, k > n, or when kth nodes from both ends are the same.
Node Location:
Find the kth node from the beginning (
x
) along with its previous node (px
).Find the kth node from the end (
y
) along with its previous node (py
).The kth node from end is at position
(n - k + 1)
from the beginning.
Pointer Adjustment:
Update previous node pointers to point to the swapped nodes.
Handle special cases when either node is the head of the list.
Node Swapping:
Swap the next pointers of both target nodes.
Update head pointer if necessary (when k = 1 or k = n).
Edge Case Handling:
Return original list if k > n or if both nodes are the same (middle node in odd-length list).
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the number of nodes in the linked list. We traverse the list a constant number of times (at most 3 passes) to count nodes, locate target nodes, and perform the swap.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for pointer variables regardless of the input size.
π§βπ» Code (C++)
class Solution {
public:
Node* swapKth(Node* head, int k) {
if (!head) return head;
int n = 0;
for (Node* t = head; t; t = t->next) n++;
if (k > n || 2 * k - 1 == n) return head;
Node *x = head, *y = head, *px = nullptr, *py = nullptr;
for (int i = 1; i < k; i++) px = x, x = x->next;
for (int i = 1; i < n - k + 1; i++) py = y, y = y->next;
if (px) px->next = y; else head = y;
if (py) py->next = x; else head = x;
Node* temp = x->next;
x->next = y->next;
y->next = temp;
return head;
}
};
β Code (Java)
class Solution {
public Node swapKth(Node head, int k) {
if (head == null) return head;
int n = 0;
for (Node t = head; t != null; t = t.next) n++;
if (k > n || 2 * k - 1 == n) return head;
Node x = head, y = head, px = null, py = null;
for (int i = 1; i < k; i++) { px = x; x = x.next; }
for (int i = 1; i < n - k + 1; i++) { py = y; y = y.next; }
if (px != null) px.next = y; else head = y;
if (py != null) py.next = x; else head = x;
Node temp = x.next;
x.next = y.next;
y.next = temp;
return head;
}
}
π Code (Python)
class Solution:
def swapKth(self, head, k):
if not head: return head
n, t = 0, head
while t: n, t = n + 1, t.next
if k > n or 2 * k - 1 == n: return head
x, y, px, py = head, head, None, None
for _ in range(k - 1): px, x = x, x.next
for _ in range(n - k): py, y = y, y.next
if px: px.next = y
else: head = y
if py: py.next = x
else: head = x
x.next, y.next = y.next, x.next
return head
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated