Swapping Nodes in a Linked List (LeetCode 1721): Solution and Explanation
Swap the values of the k-th node from the front and the k-th node from the end of a linked list. Two pointers kept k - 1 nodes apart find the node from the end in a single pass.
Intuition
The k-th node from the front is easy: start at head and take k - 1 steps.
The k-th node from the end is harder because a singly linked list cannot walk backwards. One option is to count the length n first and then walk n - k steps, which takes two passes.
A neater trick: once front is on the k-th node, it is k - 1 nodes ahead of head. Start back at head and move both pointers together. The gap never changes, so when the leading pointer reaches the tail, back is k - 1 nodes before the tail, which is the k-th node from the end.
Approach: Fixed-gap two pointers
- Walk
frontfrom head k - 1 times. It is now the k-th node from the front. - Set
fast = frontandback = head. They are k - 1 nodes apart. - While
fast.nextis not null, movefastandbackone node each. backis now the k-th node from the end. Swapfront.valandback.valand return head.
Step-by-step example
head = [1,2,3,4,5], k = 2
- front starts on 1 and takes k - 1 = 1 step, landing on 2.
- fast starts on 2 and back starts on 1, one node apart.
- Move both: fast 3, back 2. Again: fast 4, back 3. Again: fast 5, back 4. fast.next is null, so stop.
- back is on 4, the 2nd node from the end. Swap 2 and 4 to get [1,4,3,2,5].
Code: Python, Java, C++
1class Solution:
2 def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
3 front = head
4 for _ in range(k - 1):
5 front = front.next
6 fast, back = front, head
7 while fast.next:
8 fast = fast.next
9 back = back.next
10 front.val, back.val = back.val, front.val
11 return head1class Solution {
2 public ListNode swapNodes(ListNode head, int k) {
3 ListNode front = head;
4 for (int i = 1; i < k; i++) {
5 front = front.next;
6 }
7 ListNode fast = front, back = head;
8 while (fast.next != null) {
9 fast = fast.next;
10 back = back.next;
11 }
12 int tmp = front.val;
13 front.val = back.val;
14 back.val = tmp;
15 return head;
16 }
17}1class Solution {
2public:
3 ListNode* swapNodes(ListNode* head, int k) {
4 ListNode* front = head;
5 for (int i = 1; i < k; i++) {
6 front = front->next;
7 }
8 ListNode* fast = front;
9 ListNode* back = head;
10 while (fast->next) {
11 fast = fast->next;
12 back = back->next;
13 }
14 swap(front->val, back->val);
15 return head;
16 }
17};Time and space complexity
O(n)
front walks k - 1 nodes and then fast walks the remaining n - k nodes, so every node is visited about once.
O(1)
Three pointers. The swap exchanges two values in place.
Other approaches
Count the length first (time O(n), space O(1))
Walk the list once to get n, then find node k and node n - k + 1 with a second walk. Simple and also O(n), just two passes.
Copy into an array (time O(n), space O(n))
Store node references in an array and swap the values at index k - 1 and n - k. Easy to read, but uses O(n) memory.
Common mistakes
- Off-by-one in the first walk. The k-th node needs k - 1 steps from head, not k.
- Stopping when fast is null instead of when fast.next is null. That moves back one node too far.
- Swapping the nodes themselves by relinking. It is possible but needs care when the two nodes are adjacent or equal; the problem only asks for the values to change.
- Forgetting that front and back can be the same node when n is odd and k is the middle. Swapping a value with itself is harmless, so no special case is needed.
Frequently asked questions
Why does the gap trick land on the k-th node from the end?
front is node k, so it is k - 1 steps after head. Both pointers then move equally, so back always trails fast by k - 1 nodes. When fast is the last node (node n), back is node n - k + 1, which is the k-th from the end.
Can k be larger than n / 2?
Yes. Then the k-th node from the front comes after the k-th node from the end. The algorithm does not care about the order; it still swaps the same two values.
Is swapping values allowed here?
Yes. The problem asks to swap the values of the two nodes, so no pointers need to change.