Swapping Nodes in a Linked List
Medium
Topics
Given the head of a linked list and an integer k, swap the values of the k-th node from the beginning and the k-th node from the end (1-indexed), then return the head.
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
- 1 <= k <= number of nodes <= 10^5
- 0 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
The problem asks to swap values, so no relinking is needed — the work is locating the two nodes in a single pass without knowing the length in advance.
The two-pointer gap does it. Walk first forward k - 1 steps so it sits on the k-th node from the start. Now start a second pointer at the head and advance both until first reaches the tail: the gap between them is fixed, so when the leader is at the end, the follower is exactly k nodes from it — the k-th node from the end.
Approach
- Advance
firstbyk - 1to reach the k-th node from the start. - Set
secondto the head andcurtofirst. - Advance
curandsecondtogether untilcuris the last node. - Swap the two values.
Dry Run
input 1 -> 2 -> 3 -> 4 -> 5 k = 2
first walks k-1 = 1 step -> node 2
cur second
2 1
3 2
4 3
5 4 cur is the tail, so second is the 2nd node from the end
swap 2 and 4
answer 1 -> 4 -> 3 -> 2 -> 5
[7,9,6,6,7,8,3,0,9,5] k=5 -> 7 -> 9 -> 6 -> 6 -> 8 -> 7 -> 3 -> 0 -> 9 -> 5
[1] k=1 -> 1 both pointers land on the same node, a no-op
[1,2] k=1 -> 2 -> 1Complexity
- Time — O(n): one pass. The
k-1walk and the gap walk together cover the list once. - Space — O(1): three pointers.
Common Pitfalls
- Making two separate passes, one to measure the length and one to find node
n - k + 1. It is correct and still O(n), but the gap technique is the point of the exercise. - Off-by-one in the gap.
firstadvancesk - 1times, notk; and the follower stops when the leader is on the last node, not past it. - Relinking the nodes instead of swapping values. The problem asks for the values, and relinking two arbitrary nodes correctly is considerably fiddlier — especially when they are adjacent or the same node.
- Special-casing
kin the middle of the list. When both pointers land on the same node the swap is a no-op and needs no branch. - Assuming
kis within range and omitting the reasoning. The constraints guarantee1 <= k <= n, which is exactly what makes the unguardedk-1walk safe. - Collecting all values into an array, swapping, and writing back. O(n) space for a problem that needs none.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def swapNodes(self, head, k):
first = head
for _ in range(k - 1):
first = first.next
second = head
cur = first
while cur.next:
cur = cur.next
second = second.next
first.val, second.val = second.val, first.val
return headimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode swapNodes(ListNode head, int k) {
ListNode first = head;
for (int i = 0; i < k - 1; i++) first = first.next;
ListNode second = head, cur = first;
while (cur.next != null) {
cur = cur.next;
second = second.next;
}
int t = first.val;
first.val = second.val;
second.val = t;
return head;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* swapNodes(ListNode* head, int k) {
ListNode* first = head;
for (int i = 0; i < k - 1; i++) first = first->next;
ListNode* second = head;
ListNode* cur = first;
while (cur->next) {
cur = cur->next;
second = second->next;
}
int t = first->val;
first->val = second->val;
second->val = t;
return head;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/ var swapNodes = function(head, k) {
let first = head;
for (let i = 0; i < k - 1; i++) first = first.next;
let second = head, cur = first;
while (cur.next) {
cur = cur.next;
second = second.next;
}
const t = first.val;
first.val = second.val;
second.val = t;
return head;
};