InterviewPrepKit

Home / Coding / Linked List

Reverse Nodes in k-Group

hard Original ↗
Solving tips
  • Before reversing each block, walk ahead k nodes to confirm a full group exists; a final partial block stays in original order.
  • Seed the standard three-pointer reversal with group_next (the node after the block) so the reversed block's tail already points at the rest, avoiding a patch-up step.
  • Keep a dummy node and a group_prev anchor before each block; after reversing, the block's old head becomes the new group_prev.
  • Relink actual nodes (value swapping is banned); target O(n) time and O(1) space with the iterative version.

Problem

Given the head of a singly-linked list and an integer k, reverse the nodes in blocks of exactly k: the first k nodes get reversed among themselves, then the next k, and so on. If fewer than k nodes remain at the end, that tail block stays in its original order.

Two rules make it Hard: you must relink the actual nodes (swapping the values inside nodes is explicitly not allowed), and the follow-up asks for O(1) extra memory — no arrays, no recursion stack.

Examples

  • Input: head = [1, 2, 3, 4, 5], k = 2 → Output: [2, 1, 4, 3, 5] Blocks (1,2) and (3,4) are each reversed; the leftover 5 is a partial block and stays put.
  • Input: head = [1, 2, 3, 4, 5], k = 3 → Output: [3, 2, 1, 4, 5] Only (1,2,3) forms a full block; (4,5) has fewer than 3 nodes and is untouched.
  • Input: head = [1, 2, 3, 4, 5, 6], k = 1 → Output: [1, 2, 3, 4, 5, 6] Reversing blocks of one changes nothing.

Constraints

  • Number of nodes n is in [1, 5000], and 1 <= k <= n.
  • 0 <= Node.val <= 1000.
  • The follow-up that shapes the expected answer: O(n) time, O(1) extra space, nodes themselves rewired.

Think about it first

Hint 1 You already know how to reverse a whole linked list with three pointers (prev/curr/next). This problem is that same reversal, applied k nodes at a time — the new difficulty is purely in the bookkeeping between blocks.
Hint 2 Before reversing a block, check it actually has k nodes by walking ahead; if the walk falls off the list, leave the remainder alone. After reversing, the block's old first node has become its tail — and it is exactly the node that must connect to the *next* block's result.
Hint 3 Iterative O(1) recipe: keep a dummy node and a `group_prev` pointer at the node just before the current block. Find the block's k-th node, remember `group_next = kth.next`, reverse the block seeding `prev = group_next` (so the reversed block automatically points at what follows), then splice: `group_prev.next = kth`, and the old block head becomes the new `group_prev`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.