The problem. Given the head of a linked list and a number k, swap the values of the kth node from the beginning and the kth node from the end (counting from 1). Return the head.
Input: head = [1, 2, 3, 4, 5], k = 2
Output: [1, 4, 3, 2, 5]
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]Finding the kth node from the start is easy: walk k − 1 steps. The kth from the end is the tricky one, because a singly linked list can't walk backwards.
Copy every value into an array, swap positions k − 1 and n − k there, then write the values back into the nodes.
function swapNodes(head, k) { const values = []; for (let c = head; c !== null; c = c.next) values.push(c.val); const i = k - 1, j = values.length - k; [values[i], values[j]] = [values[j], values[i]]; let idx = 0; for (let c = head; c !== null; c = c.next) c.val = values[idx++]; // write back return head;}Time O(n), space O(n). It copies all n values just to swap two of them.
Count the length n. The kth from the end is the (n − k + 1)th from the start. Walk to both nodes and swap their values directly.
function swapNodes(head, k) { let n = 0; for (let c = head; c !== null; c = c.next) n++; // pass 1: length let first = head, second = head; for (let i = 1; i < k; i++) first = first.next; // kth from start for (let i = 1; i < n - k + 1; i++) second = second.next; // kth from end [first.val, second.val] = [second.val, first.val]; return head;}Time O(n), space O(1). No copy — but the list is walked twice.
Walk to the kth node from the start (first). Now start a second pointer second at the head and a runner fast at first. fast is k − 1 nodes ahead of second. Move them together until fast is on the last node: second is then k − 1 nodes before the end — the kth from the end.
Try k = 1 (swap the ends) and the middle position, where both pointers land on the same node.
Time O(n), space O(1), in one pass.
O(n)It copies all n values to swap two.
O(n)The array of all values.
O(n)All three are linear: the brute force copies every value, the optimal solution walks the list twice, and the best walks it once.
[1] with k = 1: both pointers are the same node.[1, 2, 3] with k = 2 swaps a node with itself.Two passes: count, then find both nodes.
O(1)A counter and two pointers.
O(n)A pointer k behind finds the k-th from the end in the same pass.
O(1)Only three pointers.