Skip to problem
←

Reverse Nodes in k-Group

Hard 0 attempts

Given a nonempty singly linked list and an integer k, divide the list from its head into consecutive groups of k nodes. Reverse each complete group and return the resulting head.

If the final group has fewer than k nodes, leave it in its original order. Rewire the original nodes without changing their values or creating replacements. Use constant extra space.

For [1, 2, 3, 4, 5] and k = 2, return [2, 1, 4, 3, 5]. With k = 3, return [3, 2, 1, 4, 5]: the final two nodes remain unchanged. With k = 1, the whole list stays unchanged.

Your function receives nodes with val and next properties; examples display value arrays.

Function contract

Implement reverseKGroup(head, k). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head after reversing every complete group of k original nodes. Preserve node values and leave any shorter final group unchanged.

Example 1

Input
head = [1,2,3,4,5]
k = 2
Output
[2,1,4,3,5]

Example 2

Input
head = [1]
k = 1
Output
[1]
Constraints
  • 1 <= n <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= n
Topics

Verify Each Group, Then Reverse It

Keep prev immediately before the next group, initially a dummy head. Look ahead k nodes before changing any links. If fewer remain, return immediately so the incomplete suffix stays untouched.

For a complete group, keep its first node as curr and move each of the next k - 1 nodes to the group's front, directly after prev. The old first node becomes the reversed group's tail; move prev there to process the next group.

Each node participates in at most one look-ahead scan and one group reversal. The algorithm uses only pointers, preserves every original node and value, and handles k = 1 without special allocation.

javascript
function reverseKGroup(head, k) {
  const dummy = { next: head };
  let prev = dummy;
  while (true) {
    let kth = prev;
    for (let i = 0; i < k; i++) {
      kth = kth.next;
      if (!kth) return dummy.next;
    }
    let curr = prev.next,
      next = curr.next;
    for (let i = 0; i < k - 1; i++) {
      curr.next = next.next;
      next.next = prev.next;
      prev.next = next;
      next = curr.next;
    }
    prev = curr;
  }
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript