Reverse Nodes in k-Group
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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Recursive | O(n) | O(n / k) |
| Optimal (iterative, group by group) | O(n) | O(1) |
1Recursive
O(n)O(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.
- Count k nodes from head; if fewer, return head.
- 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;
}
}class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
p = head
for _ in range(k):
if not p:
return head
p = p.next
prev, cur = self.reverseKGroup(p, k), head
for _ in range(k):
next = cur.next
cur.next = prev
prev = cur
cur = next
return prevclass Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* p = head;
for (int i = 0; i < k; i++) {
if (p == nullptr) return head;
p = p->next;
}
ListNode* prev = reverseKGroup(p, k);
ListNode* cur = head;
for (int i = 0; i < k; i++) {
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};function reverseKGroup(head, k) {
let p = head;
for (let i = 0; i < k; i++) {
if (p === null) return head;
p = p.next;
}
let prev = reverseKGroup(p, k), cur = head;
for (let i = 0; i < k; i++) {
const next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}2Optimal (iterative, group by group)
O(n)Each node is visited a constant number of times.O(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.
- kth = k steps from groupPrev; if null, break.
- groupNext = kth.next; reverse nodes from groupPrev.next up to kth with prev starting at groupNext.
- 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;
}
}class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
groupPrev = dummy
while True:
kth = groupPrev
i = 0
while i < k and kth:
kth = kth.next
i += 1
if not kth:
break
groupNext = kth.next
prev, cur = groupNext, groupPrev.next
while cur is not groupNext:
next = cur.next
cur.next = prev
prev = cur
cur = next
first = groupPrev.next
groupPrev.next = kth
groupPrev = first
return dummy.nextclass Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0, head);
ListNode* groupPrev = dummy;
while (true) {
ListNode* kth = groupPrev;
for (int i = 0; i < k && kth != nullptr; i++) kth = kth->next;
if (kth == nullptr) break;
ListNode* groupNext = kth->next;
ListNode* prev = groupNext;
ListNode* 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;
}
};function reverseKGroup(head, k) {
const dummy = new ListNode(0, head);
let groupPrev = dummy;
while (true) {
let kth = groupPrev;
for (let i = 0; i < k && kth !== null; i++) kth = kth.next;
if (kth === null) break;
const groupNext = kth.next;
let prev = groupNext, cur = groupPrev.next;
while (cur !== groupNext) {
const next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
const 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.