Problem Description
Given the head of a linked list and an integer k, swap the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Return the head of the modified list.
Key Insights
- Use a two-pointer technique to identify the kth node from the beginning and the kth node from the end.
- First, traverse the list to reach the kth node from the beginning.
- Then, use a pointer starting at the kth node and a second pointer starting at the head to reach the kth node from the end by moving them until the first pointer reaches the end.
- Swap the values of the two identified nodes.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
The solution uses the two-pointer approach to efficiently locate the two nodes whose values need to be swapped. First, traverse from the head and stop at the kth node (this is the kth node from the beginning). Save a reference to this node. Next, start a new pointer at the head and simultaneously traverse from the kth node to the end of the list. When the latter pointer reaches the end, the pointer started at the head will be at the kth node from the end. Finally, swap the values of these two nodes. The swap is done in place without altering the list structure, which ensures an O(1) space complexity.