← Questions

Reverse nodes in k-group

0
MicrosoftCodingLast asked Oct 2025

A coding interview question asked in Microsoft's coding round, last asked Oct 2025. It tests linked lists and pointers.

Given the head of a singly linked list and an integer k, reverse the nodes in each consecutive block of k nodes and return the new head. If fewer than k nodes remain at the end, leave them in their original order. Change the links, not the values, and use O(1) extra space.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • class ListNode: val: int; next: ListNode | None
  • reverse_k_group(head: ListNode | None, k: int) -> ListNode | None

Example

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7, k = 3   ->  3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 7
1 -> 2 -> 3, k = 1                        ->  1 -> 2 -> 3
1 -> 2, k = 3                             ->  1 -> 2

Constraints

  • 0 <= n <= 10^5 nodes, 1 <= k.
  • O(n) time; O(1) extra space, not counting a recursion stack if you choose recursion.

Clarifying questions

  • Is k ever larger than the list length?
  • May I change node values, or must I relink nodes?
  • Is a recursive solution acceptable, or must stack depth stay constant?

What a strong answer covers

  • A dummy head, then a loop: check that k nodes remain, reverse that block in place, and reconnect the previous block's tail to the new block head and the block's new tail to what follows.
  • Careful pointer bookkeeping, explained before coding.
  • O(n) time, O(1) space; why the recursive version uses O(n/k) stack.
  • Tests: k = 1, k equal to the length, a length that is an exact multiple of k, an empty list.

Follow-ups

  • Reverse the final short group too.
  • Reverse every other group of k.
  • Reverse only the nodes between positions m and n.

Where it's asked

  • Microsoft · Coding · Last asked Oct 202560 min · Ten to fifteen minutes of behavioral questions, then coding in HackerRank where you write a main and make the tests pass; usually three rounds · No AI unless the interviewer invites it; some 2026 loops add a round where you bring your own AI agent

What it tests

linked lists · pointers

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding