Reverse Nodes in k-Group

HardLinked List · In-place Reversal🧩 Linked List TechniquesLeetCode #25 ↗Updated

Problem

Split a singly linked list into consecutive blocks of k nodes and reverse the order of nodes inside each full block. A trailing block shorter than k stays as it is. Rearrange the nodes themselves — changing only the values is not allowed.
Input[1,2,3,4,5], k=2Output[2,1,4,3,5]
Input[1,2,3,4,5], k=3Output[3,2,1,4,5]

1 ≤ k ≤ n ≤ 5000  ·  0 ≤ Node.val ≤ 1000  ·  Follow-up: O(1) extra memory.

Try it yourself

Java
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Know the length up front so you only touch full groups. Then reverse each group in place by repeatedly moving the node after the group's original first node to the front of the group — k-1 moves per group, all via a fixed prev anchor.
PatternLinked List Techniques

Instinct Nodes joined by next pointers and the task is to reverse, splice, merge, reorder or remove in place - grab a dummy head and rewire pointers carefully.

Memory hack Save next, flip, step - never let go of a rope before you've grabbed the next one.

Open the Linked List Techniques guide →

Approaches

Brute ForceNode Array, Reverse Chunks, Relink

Time O(n)Space O(n)

Copy all node references into an array. Reverse every full window [i, i+k) of the array with two pointers, leave the tail window alone, then rebuild the chain in array order. Nodes move, values don't.

Java
public ListNode reverseKGroup(ListNode head, int k) {
    List<ListNode> nodes = new ArrayList<>();
    for (ListNode c = head; c != null; c = c.next) nodes.add(c);
    int n = nodes.size();
    for (int start = 0; start + k <= n; start += k) {
        for (int l = start, r = start + k - 1; l < r; l++, r--) {
            Collections.swap(nodes, l, r);
        }
    }
    for (int i = 0; i < n - 1; i++) nodes.get(i).next = nodes.get(i + 1);
    nodes.get(n - 1).next = null;
    return nodes.get(0);
}

Simple and linear, but the array breaks the O(1)-memory follow-up.

At a glance

LevelApproachTimeSpace
Brute ForceNode Array, Reverse Chunks, RelinkO(n)O(n)
BetterRecursion per GroupO(n)O(n/k)
OptimalIterative Head-Insertion with DummyO(n)O(1)
Common pitfalls
  • Reversing the last partial group — check that k nodes remain before reversing.
  • Losing the link from the previous group's tail to the new group head.
  • Forgetting a dummy node — the first group changes the list's head.
Interview tips
  • Reduce to a known sub-problem: “reverse k nodes between two anchors”.
  • Mention the recursive version first, then improve to O(1) space for the follow-up.
  • Test k=1 (no change), k=n (full reverse) and n not divisible by k.
Pattern
Dummy + group-wise in-place reversal → reverse fixed-size or ranged segments of a list.
My notes saved in this browser