Reverse Nodes in k-Group

Hard#25reverse

You get a linked list and a number k. Reverse the nodes in groups of k: the first k, then the next k, and so on. If fewer than k nodes are left at the end, they keep their order. Only links may change, not the values. Our example: 4 → 1 → 7 → 3 → 9 → 2 → 8 → 5, k = 3 — the answer is 7 → 1 → 4 → 2 → 9 → 3 → 8 → 5.

input
head: the head of a linked list of n nodes; k: the size of a group.
returns
The head of the list with every k nodes in a row reversed, from its start; the nodes left at the end, fewer than k, stay as they are.
constraints
  • 1 ≤ n ≤ 1000
  • 1 ≤ k ≤ n
  • 0 ≤ Node.val ≤ 1000
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
function reverseKGroup(head, k) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more linked list pointers problems

Pattern “Linked list pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.