Swapping Nodes in a Linked List - Problem
Imagine you have a chain of connected nodes, and you need to perform a symmetric swap operation. You're given the head of a linked list and an integer k.
Your task is to swap the values of two specific nodes:
- The
kth node from the beginning (1-indexed) - The
kth node from the end (1-indexed)
For example, in a list [1,2,3,4,5] with k=2, you would swap the 2nd node from start (value 2) with the 2nd node from end (value 4), resulting in [1,4,3,2,5].
Important: You only need to swap the values, not the actual node positions. Return the head of the modified linked list.
Input & Output
example_1.py โ Basic Case
$
Input:
head = [1,2,3,4,5], k = 2
โบ
Output:
[1,4,3,2,5]
๐ก Note:
Swap the 2nd node from beginning (value 2) with 2nd node from end (value 4). The result is [1,4,3,2,5].
example_2.py โ Middle Element
$
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]
๐ก Note:
Swap the 5th node from beginning (value 7) with 5th node from end (value 8). In a 10-node list, 5th from end is 6th from beginning.
example_3.py โ Single Node
$
Input:
head = [1], k = 1
โบ
Output:
[1]
๐ก Note:
With only one node, the 1st from beginning and 1st from end are the same node. Swapping it with itself results in no change.
Constraints
-
The number of nodes in the list is
n - 1 โค n โค 105
- 0 โค Node.val โค 100
- 1 โค k โค n
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Pointers
Both pointers start at the head of the linked list
2
Create Gap
Move first pointer k steps ahead, creating a k-node gap
3
Save Reference
Store reference to the kth node from beginning
4
Move Together
Advance both pointers until first reaches the end
5
Swap Values
Second pointer is now at kth from end, swap the values
Key Takeaway
๐ฏ Key Insight: The gap technique automatically positions the second pointer at the kth node from the end when the first pointer reaches the end, eliminating the need for list length calculation.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code