Reverse Nodes in k-Group solution explained

Reverse Nodes in k-Group is solved by handling the list one block of k nodes at a time: first check that k nodes remain, then reverse just that block in place and stitch it back between the node before it and the node after it. A final block shorter than k stays as it is. Each node is visited a constant number of times, so the time is O(n) and the extra memory is O(1).

By Published 6 min read

The problem in your own words

You get a singly linked list and a positive whole number k. Split the list into consecutive blocks of k nodes from the front. Reverse the order of the nodes inside every full block. If the last block has fewer than k nodes, leave it in its original order. You must rearrange the nodes themselves rather than overwrite their values, and you should return the new head.

Examples written for this page
ListkResult
1 → 2 → 3 → 4 → 5 → 6 → 733 → 2 → 1 → 6 → 5 → 4 → 7
1 → 2 → 3 → 422 → 1 → 4 → 3
1 → 2 → 341 → 2 → 3 (no full block)
1 → 2 → 311 → 2 → 3 (blocks of one change nothing)
Examples written for this page. Scroll sideways on a small screen.

Why it shows up in harder rounds

Plain list reversal is a warm-up. Doing it in blocks raises the stakes: you must reverse a bounded segment, reconnect it to what came before and after, and move on without losing track of four different nodes. Interviewers use it to see whether your pointer code stays readable under pressure, and whether you can test it by drawing boxes and arrows rather than by guessing.

Variations

  • Reverse the final short block too. Drop the k-node probe and reverse whatever is left.
  • Reverse only between positions left and right. One block instead of many, with the same reconnect step.
  • Swap every two adjacent nodes. The special case k = 2, often asked first.
  • Recursive version. Reverse the first block, then recurse on the rest. Clean, but it uses O(n / k) stack space.

A baseline that moves values

Copy the values into an array, reverse each full chunk of k entries, and write the values back into the nodes in order. It is correct and O(n), and it is a fine way to make sure you understand the expected output. It breaks the usual rule of moving nodes, and it needs O(n) extra memory, so present it as a stepping stone.

def reverse_k_group_values(head, k):
    values, node = [], head
    while node:
        values.append(node.val)
        node = node.next
    for start in range(0, len(values) - k + 1, k):
        values[start:start + k] = values[start:start + k][::-1]
    node = head
    for v in values:
        node.val = v
        node = node.next
    return head
Array baseline: correct output, but values are rewritten.

In-place reversal, block by block

Use a sentinel before the head and a pointer called before that marks the node just ahead of the current block. Each round has four steps. Probe: walk k nodes from before; if you run out, you are done. Name the ends: first is before.next, last is the node the probe reached, and after is last.next. Reverse: run the usual three-pointer reversal over the block, but start prev at after instead of at nothing, so the reversed block already points to the rest of the list. Reconnect: set before.next to last, then move before to first, which is now the block's tail.

class Node:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def reverse_k_group(head, k):
    sentinel = Node(0, head)
    before = sentinel  # node just before the group being handled
    while True:
        probe = before
        for _ in range(k):  # is there a full group ahead?
            probe = probe.next
            if probe is None:
                return sentinel.next
        first = before.next
        after = probe.next
        prev, cur = after, first
        while cur is not after:  # reverse the k nodes in place
            cur.next, prev, cur = prev, cur, cur.next
        before.next = probe  # old last node now leads the group
        before = first       # old first node now ends it
Python: O(n) time, O(1) extra memory.
class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

function reverseKGroup(head, k) {
  const sentinel = new ListNode(0, head);
  let before = sentinel;
  while (true) {
    let probe = before;
    for (let i = 0; i < k; i++) {
      probe = probe.next;
      if (probe === null) return sentinel.next;
    }
    const first = before.next;
    const after = probe.next;
    let prev = after;
    let cur = first;
    while (cur !== after) {
      const nxt = cur.next;
      cur.next = prev;
      prev = cur;
      cur = nxt;
    }
    before.next = probe;
    before = first;
  }
}
JavaScript: the same four steps.

A note on the Python tuple assignment: the right side is evaluated first, then targets are assigned left to right, so cur.next is written while cur still names the old node. If that line feels too clever to explain, use a temporary variable as in the JavaScript version.

Cost

Time and extra memory
ApproachTimeExtra memoryMoves nodes?
Array of valuesO(n)O(n)No, rewrites values
Recursive block reversalO(n)O(n / k) call stackYes
Iterative block reversalO(n)O(1)Yes
Time and extra memory. Scroll sideways on a small screen.

The probe walks each block once and the reversal walks it again, so every node is touched about twice. That is still linear.

Cases to test

  • k = 1, which must return the list unchanged.
  • k equal to the length, which reverses the whole list.
  • k larger than the length, which changes nothing.
  • A length that is an exact multiple of k, so there is no leftover block.
  • An empty list.

Where people go wrong

  • Starting the reversal with prev as nothing, which cuts the block off from the rest of the list.
  • Moving before to the old last node instead of the old first node after the reconnect.
  • Reversing a short final block because the probe step was skipped.
  • Losing the next node during reversal by overwriting cur.next before saving it.

How to explain it out loud

Fictional example

Explaining while drawing
Candidate
I will handle one block at a time. First I check that k nodes exist ahead; if not, the rest stays as it is and I am finished.
Candidate
For a full block I remember the node before it and the node after it. I reverse the block with prev starting at the node after, so the new tail is already linked onward.
Candidate
Then the node before points to the old last node, and the old first node becomes the new before. Every node is touched a couple of times, so it is linear with constant extra space.

Where to go next

Remove Nth Node From End of List is a gentler warm-up with the same sentinel. Merge k Sorted Lists moves the focus from rewiring one list to combining many.

Rehearse it with Natively

Pointer problems like this one are easier to get right when you narrate a drawing. During practice, Natively on Mac or Windows can read the problem from a screenshot and lay out the probe, reverse and reconnect steps alongside the cases that usually break, so you can check your own plan against it. If you rehearse aloud, the transcript shows whether your explanation kept the four pointers straight. See the AI interview assistant.

Questions people ask

How do you solve Reverse Nodes in k-Group?

Handle one block at a time: check that k nodes remain, reverse those k nodes in place with prev starting at the node after the block, then link the node before the block to the old last node.

What happens to the last group if it has fewer than k nodes?

In the usual version it stays in its original order. The probe step that checks for k nodes is what makes the loop stop there.

What is the time and space complexity?

O(n) time, since every node is visited about twice, and O(1) extra memory for the iterative version. A recursive version uses O(n / k) stack.

Can I just swap the values instead of the nodes?

It gives the right sequence of values, but the problem normally asks you to move nodes, and interviewers treat value swapping as a shortcut.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP