Reverse nodes in k-group
Hard TimeO(n) SpaceO(n/k) stack
Given the head of a linked list and a number k, reverse its nodes in blocks of k and return the new head — [1, 2, 3, 4, 5] with k = 2 becomes [2, 1, 4, 3, 5]. Only complete groups are reversed, so a short final group stays exactly as it is, and every reversed block has to be joined to the one before it.
Examples
Example 1
- Input
- node = reverseKGroup(buildList([1, 2, 3, 4, 5]), 2)
- Output
[2,1,4,3,5]1, 2becomes2, 1and3, 4becomes4, 3; the lone5is short of a group and stays.
Example 2
- Input
- node = reverseKGroup(buildList([1, 2, 3, 4, 5]), 3)
- Output
[3,2,1,4,5]1, 2, 3becomes3, 2, 1, and4, 5is short of 3 so it is left alone.
The Code
function buildList(values) {
let head = null;
for (let i = values.length - 1; i >= 0; i--) {
head = { val: values[i], next: head };
}
return head;
}
function toArray(node) {
const out = [];
while (node) {
out.push(node.val);
node = node.next;
}
return out;
}
function reverseKGroup(head, k) {
let node = head;
for (let i = 0; i < k; i++) {
if (node === null) return head;
node = node.next;
}
let prev = reverseKGroup(node, k);
let current = head;
for (let i = 0; i < k; i++) {
const nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev;
}
toArray(reverseKGroup(buildList([1, 2, 3, 4, 5]), 2));More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Detect a cycle A slow and a fast pointer must meet if the list loops.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Merge two lists A dummy head removes every special case for the first node.
- Remove nth from end Open an n-node gap between two pointers, then walk them together.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.