InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Linked List

Reverse Nodes in k-Group

hard Original ↗ 00:00

Problem

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

Two constraints make this hard. You must relink the actual nodes (swapping the values inside nodes is 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.
  • Follow-up target for the expected answer: O(n) time, O(1) extra space, with the nodes themselves rewired.

Think about it first

Hint 1 Reversing a whole linked list takes three pointers (prev/curr/next). This problem is that same reversal applied k nodes at a time; the added difficulty is the bookkeeping between blocks.
Hint 2 Before reversing a block, walk ahead to confirm it has k nodes; if the walk falls off the list, leave the remainder alone. After reversing, the block's old first node becomes its tail, and that tail is the node that must connect to the *next* block's result.
Hint 3 Iterative O(1) approach: keep a dummy node and a `group_prev` pointer at the node just before the current block. Find the block's k-th node, record `group_next = kth.next`, reverse the block with `prev` seeded to `group_next` so the reversed block points at what follows, then splice with `group_prev.next = kth`. The old block head becomes the new `group_prev`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug