Reverse Nodes in k-Group

Hard Linked List Front Middle Back Pointer Original on LeetCode

Reverse Nodes in k-Group is a hard linked list problem solved with the front middle back pointer pattern. The best approach, optimal (iterative, group by group), runs in O(n) time and O(1) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from recursive up.

Problem

Reverse the nodes of a linked list k at a time. If the number of nodes left at the end is less than k, leave them as they are. Change links, not values.

Examples

Example 1

Input
head = [1, 2, 3, 4, 5], k = 2
Output
[2, 1, 4, 3, 5]

Example 2

Input
head = [1, 2, 3, 4, 5], k = 3
Output
[3, 2, 1, 4, 5]
Why
The last group has only 2 nodes, so it stays as is.

Constraints

  • 1 <= k <= n <= 5000
  • Change links, not values. Follow-up: O(1) extra memory.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
RecursiveO(n)O(n / k)
Optimal (iterative, group by group)O(n)O(1)

1Recursive

TimeO(n)
SpaceO(n / k)Recursion depth is the number of groups.

Check that k nodes exist, reverse them, and attach the recursively processed rest to the new tail.

  1. Count k nodes from head; if fewer, return head.
  2. Reverse those k nodes; head (now the tail) .next = recurse(rest).
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode p = head;
        for (int i = 0; i < k; i++) {
            if (p == null) return head;
            p = p.next;
        }
        ListNode prev = reverseKGroup(p, k), cur = head;
        for (int i = 0; i < k; i++) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}

2Optimal (iterative, group by group)

TimeO(n)Each node is visited a constant number of times.
SpaceO(1)

groupPrev is the node before the group. Find the k-th node; if it is missing, stop. Reverse the group by pointing its first node at the node after the group, then relink groupPrev to the new front and move groupPrev to the new tail.

  1. kth = k steps from groupPrev; if null, break.
  2. groupNext = kth.next; reverse nodes from groupPrev.next up to kth with prev starting at groupNext.
  3. first = groupPrev.next; groupPrev.next = kth; groupPrev = first.
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0, head), groupPrev = dummy;
        while (true) {
            ListNode kth = groupPrev;
            for (int i = 0; i < k && kth != null; i++) kth = kth.next;
            if (kth == null) break;
            ListNode groupNext = kth.next, prev = groupNext, cur = groupPrev.next;
            while (cur != groupNext) {
                ListNode next = cur.next;
                cur.next = prev;
                prev = cur;
                cur = next;
            }
            ListNode first = groupPrev.next;
            groupPrev.next = kth;
            groupPrev = first;
        }
        return dummy.next;
    }
}

Edge cases to test

  • k = 1 (no change)
  • k = n (reverse everything)
  • A short final group

Hints

Hint 1

Before reversing a group, check that k nodes exist. Keep a pointer to the node before the group so you can reconnect it.

FAQ

What is the best time complexity for Reverse Nodes in k-Group?

Optimal (iterative, group by group) runs in O(n) time and O(1) extra space. Each node is visited a constant number of times.

Which pattern does Reverse Nodes in k-Group use?

It is a linked list problem that uses the front middle back pointer pattern. Other problems with the same pattern: Reverse Linked List, Reverse Linked List II, Palindrome Linked List.

Is there a brute force solution for Reverse Nodes in k-Group?

Yes. Recursive takes O(n) time and O(n / k) space. Check that k nodes exist, reverse them, and attach the recursively processed rest to the new tail.

Which edge cases should I test for Reverse Nodes in k-Group?

k = 1 (no change); k = n (reverse everything); A short final group.