Quick revision
The short answer
Reversing a linked list in groups of k is solved by in-place pointer rewiring on segments. For each full group we reverse it with the usual three-reference loop, starting prev at the node after the group so the group stays tied to the rest, then link the node before the group to its new first node. It takes O(n) time and O(1) extra space; a short last group is left as it is.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Copy values, reverse blocks, write back (brute force) | O(n) | O(n) |
| Stack of k nodes per group | O(n) | O(k) |
| Recursion, one call per group | O(n) | O(n / k) call stack |
In place with groupPrev, kth and groupNext | O(n) | O(1) |
What to remember
We reversed a linked list in groups of k by walking k steps to prove each group was full, reversing it with prev starting at the node after the group so its back stayed tied on, and then pointing the node before the group at its new first node. A dummy node gave the first group a node in front of it, and the whole method takes O(n) time and O(1) space. The clue to remember is a change to a segment of a list: put a finger on the node before it and the node after it, change the inside, then tie both ends back on.
1What it means to reverse a list in groups
Picture a train in a shunting yard. Each coach is coupled only to the coach behind it, and the yard master must turn the coaches around three at a time: the first three coaches swap their order, then the next three, and so on, while the train stays one train. If fewer than three coaches are left at the end, they stay as they are. The hard part is keeping each turned block coupled to the coaches on either side.
A singly linked list is that train. Each node, our coach, holds a value and a reference called next, a variable that names the node after it. The first node is the head, and the last node's next is null, meaning nothing. We are given the head and a positive number k, and we must reverse the nodes of each consecutive group of k, returning the new head.
Let us keep one example for the whole article: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 with k = 3. The groups are 1, 2, 3, then 4, 5, 6, and then 7 alone. The first group becomes 3, 2, 1, the second becomes 6, 5, 4, and the short group stays 7. So the answer is 3 -> 2 -> 1 -> 6 -> 5 -> 4 -> 7.
Do it once on paper. Draw seven boxes with arrows. Redraw the arrows of the first three backwards, and notice that node 1, once the front of the group, is now its back, so its arrow must go to node 4. Do the same for 4, 5, 6, whose back, node 4, must point to node 7. And whatever pointed to the front of a group must now point to its new front. Those two ties are all the new work.
Top row: the list we are given, its two full groups marked. Bottom row: the answer, made of the same seven nodes.
1The groups of 3 are 1 2 3 and 4 5 6, and 7 is a short group. Each full group is reversed and 7 stays, giving 3 2 1 6 5 4 7.
What to assume
- What happens to a last group shorter than k?
- The common rule, which we follow, is to leave it unchanged.
- Do we move links or swap values?
- Links.
- Can k be 1, or larger than the list?
- Yes, and in both cases the list comes back unchanged.
- Can k be zero or negative?
- No. A group needs at least one node, so the code refuses such a k with an exception.
- Can the list be empty?
- Yes, and we return null.
A careful candidate asks a few questions first. What happens to a last group shorter than k? The common rule, which we follow, is to leave it unchanged; a follow-up at the end reverses it too. Do we move links or swap values? Links. Can k be 1, or larger than the list? Yes, and in both cases the list comes back unchanged. Can k be zero or negative? No, because a group needs at least one node, so the code refuses such a k with an exception. Can the list be empty? Yes, and we return null.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a segment rewiring problem
A beginner who can reverse a whole list often runs that loop once per group and gets lost at the group boundaries. That is a good instinct with a missing piece, and the clues tell us what the piece is. Let us read them one at a time.
The first clue is the word reverse. In a linked list the order lives entirely in the next references, so reversing means turning arrows around, the job of the three-reference loop with prev, curr and next.
The second clue is the phrase in groups of k. It cuts the list into pieces, called segments, each a run of neighbouring nodes. A segment has two neighbours outside it: the node just before it and the node just after it. Whenever we change a segment, those two neighbours are where the trouble happens, because their links must be updated too.
The third clue is the word nodes. We are asked to reverse the nodes, not the values, so the work must happen in place, by changing next references, without building a second list.
Together these clues point to the linked lists family and to in-place pointer rewiring on segments. A pointer, in Java, is a reference variable that names a node, like a finger resting on one coach. Rewiring means changing what a node's next refers to. The general rule to carry to new problems is this: before changing a segment, put a finger on the node before it and the node after it, change the inside, and then tie both ends back on.
Other patterns look possible but cost more. A stack of k nodes per group, like a pile of plates where the last on is the first off, reverses each group easily but uses O(k) extra space. Recursion, one call per group, is elegant but keeps one waiting call per group on the stack. Fast and slow pointers find middles and loops; they do not help with fixed-size groups.
3The honest first attempt, reversing the values in an array
When pointers feel risky, a sensible first move is to step around them. The brute force copies every value into an ArrayList, which can be reached by index, reverses each full block of k values inside it, and writes the values back into the nodes in their new order. No arrow ever changes, so nothing can be lost, and it is easy to check.
Let us do it by hand. The copy gives [1, 2, 3, 4, 5, 6, 7]. The block loop reverses positions 0 to 2 and then 3 to 5, giving [3, 2, 1, 6, 5, 4, 7]. A block at 6 would need positions up to 8, so the loop stops and 7 stays.
Now let us count. Copying visits 7 nodes, reversing the blocks touches 6 values, and writing back visits 7 nodes again, about 20 small steps. For n nodes that is about 3n steps, so the time is O(n), read as order n, meaning the work grows in step with the length. But the ArrayList holds all n values, so the extra memory, called the space, is O(n).
Where is the waste? Not in the time, because every node must be visited anyway. It is in the memory, a whole copy kept only to read pieces of it backwards, and in the kind of work, because values moved while the nodes stayed put. Code holding a reference to the node with 1 now finds 3 in it. So we need to turn the arrows, and to do that safely we must understand exactly what goes wrong at a group boundary.
4Getting to the in-place solution, one tie at a time
Let us recall plain reversal first. We keep prev, the reversed part, starting at null, and curr, the next node to turn. Each step saves next = curr.next, points curr.next back at prev, and moves prev and curr one node along. When curr reaches the end, prev is the new head.
The first new idea is that we must know a group is full before touching it. So we keep a finger called groupPrev on the node just before the group and walk k steps from it. If we land on a node, it is the group's last, which we call kth, and kth.next, the first node after the group, we call groupNext. If we run out of nodes first, we stop.
Now the question every beginner asks. Why not run the plain reversal loop on the group, prev starting at null, and fix things afterwards? Let us try it on the first group and see what we lose.
The first frame is the mistake. The second and third frames are what the real code does.
- from D
- D 1
- cut off
- nodes 2, 3 and 4 to 7
1Suppose we reverse nodes 1, 2 and 3 with the plain loop, prev starting at null. Node 1 now points to nothing, and D still points to node 1.
- from D
- D 1 4 5 6 7
- from node 3
- 3 2 1 4 5 6 7
2Now start prev at
gNext, node 4, instead of null. After the same three turns node 1 points to node 4, so the group stays tied to the rest.- from D
- D 3 2 1 4 5 6 7
3One more link,
D.next= kth, ties the front. From D the list reads 3 2 1 4 5 6 7, and nothing has been lost.
In the first frame the group 1, 2, 3 is reversed, but node 1 points to null, as it would at the end of a whole list. Two ties are broken. The back of the group, node 1, no longer reaches node 4, and the node before the group, D, still points to node 1, so the list read from D is just D 1.
The second new idea repairs the back tie for free. Plain reversal starts prev at null because the old head must end up pointing at nothing. In a group, the old first node must end up pointing at groupNext instead. So we start prev at groupNext. The very first turn then sets node 1's next to node 4, and the group is tied to the rest of the list from the moment it is turned.
The third idea repairs the front tie. After the group is turned, groupPrev.next must point to the group's new first node, which is kth. But before we change it, we save oldFirst = groupPrev.next, the node that used to be first. Why save it? Because once groupPrev.next names kth, reaching the old first node would mean walking the group again, and that node, now the group's last, is exactly the node before the next group, so it becomes the new groupPrev. Writing groupPrev = kth instead is the most common bug here, and it attaches the next group in the wrong place.
The very first group has no node in front of it. Rather than writing a special case, we put a dummy node, a spare node that holds no real value, in front of the head. groupPrev starts on the dummy, every group is handled the same way, and at the end dummy.next is the new head.
Why is this correct? Before each round, everything from the dummy up to groupPrev is finished and correctly linked, and groupPrev.next is the first node not yet processed. A round turns exactly the next k nodes, ties the group's back to groupNext and its front to groupPrev, and moves groupPrev to the group's new last node, so the statement is true again for the next round. When fewer than k nodes remain, they are already linked after groupPrev, untouched.
5Watching the groups turn around
The picture plays the code on 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 with k = 3. Only the arrows change. An arrow drawn above the row points backwards, one drawn below skips forward over other nodes, and a slash means null. gPrev, kth and gNext stand for groupPrev, kth and groupNext, and the panel reads the list by following the arrows from D.
The first group is shown one turn per frame, so you can see prev begin at node 4. The second group runs the same three turns, shown together in one frame.
Nodes never move. The current group is marked; finished groups are marked as done; D is the dummy node.
- gPrev
- D
- kth
- -
- gNext
- -
- from D
- D 1 2 3 4 5 6 7
1We begin with a dummy node D in front of node 1, so the first group has a node before it too.
gPrev, the node before the current group, starts on D.- gPrev
- D
- kth
- node 3
- gNext
- node 4
- from D
- D 1 2 3 4 5 6 7
2Walking 3 steps from D lands on node 3, so a full group exists: kth is node 3 and
gNext, the first node after the group, is node 4. prev starts on node 4, curr on node 1.- gPrev
- D
- kth
- node 3
- gNext
- node 4
- from D
- D 1 4 5 6 7
3The first turn saves node 2, points node 1 at prev, which is node 4, then steps prev onto node 1 and curr onto node 2. Node 1 already links to the rest.
- gPrev
- D
- kth
- node 3
- gNext
- node 4
- from D
- D 1 4 5 6 7
4The second turn points node 2 back at node 1, then steps prev onto node 2 and curr onto node 3.
- gPrev
- D
- kth
- node 3
- gNext
- node 4
- from D
- D 1 4 5 6 7
5The third turn points node 3 back at node 2. curr is now node 4, which is
gNext, so the inner loop stops. D still points to node 1.- gPrev
- node 1
- kth
- node 3
- gNext
- node 4
- from D
- D 3 2 1 4 5 6 7
6Now
D.next= kth makes D point to node 3, andgPrevmoves to node 1, the old first node and now the group's last. From D the list reads 3 2 1 4 5 6 7.- gPrev
- node 1
- kth
- node 6
- gNext
- node 7
- from D
- D 3 2 1 4 5 6 7
7Walking 3 steps from node 1 lands on node 6, so the second group is full: kth is node 6,
gNextis node 7, prev starts on node 7 and curr on node 4.- gPrev
- node 1
- kth
- node 6
- gNext
- node 7
- from D
- D 3 2 1 4 7
8The same three turns run on nodes 4, 5 and 6: node 4 now points to node 7, node 5 to node 4, and node 6 to node 5. curr reaches node 7 and stops.
- gPrev
- node 4
- kth
- node 6
- gNext
- node 7
- from D
- D 3 2 1 6 5 4 7
9Node 1, the last node of the first group, now points to node 6, and
gPrevmoves to node 4. From D the list reads 3 2 1 6 5 4 7.- gPrev
- node 4
- kth
- -
- gNext
- -
- from D
- D 3 2 1 6 5 4 7
10Walking from node 4 finds node 7 and then null before 3 steps, so fewer than k nodes remain. The loop stops and node 7 stays as it is.
- gPrev
- node 4
- kth
- -
- gNext
- -
- from D
- D 3 2 1 6 5 4 7
11We return
dummy.next, which is node 3. The answer is 3 2 1 6 5 4 7: two full groups reversed and the short group left alone.
Let us read the first round back. In the second frame prev starts on node 4, not null, so in the third frame the first turn already points node 1 at node 4. In the fifth frame the group is reversed and tied to the rest, but D still points to node 1, so from D we would read only D 1 4 5 6 7. The sixth frame fixes that with D.next = kth, and gPrev moves to node 1.
The second round repeats these steps one group along, ending with node 1 pointing at node 6. In the tenth frame the walk from node 4 reaches node 7 and then null after only two steps, so the group is short and we stop. Node 7 keeps its null arrow, and from D the list reads 3 2 1 6 5 4 7.
6The Java solution, read line by line
Here is the complete program, with a small Node class, the reverseKGroup method, and two helpers: build makes a list from values and show prints one. main runs our example, k = 2 on five nodes, a list whose length is a multiple of k, k = 1, k larger than the list, and an empty list. Each comment shows what that line prints.
Let us read reverseKGroup in the order it runs. The first line refuses a k below 1 by throwing an IllegalArgumentException, because a group of no nodes has no meaning and the loop below would never end. Then we create the dummy, point it at head, and put groupPrev on it. The while (true) loop handles one group per round and leaves only through the break.
At the top of each round, kth starts on groupPrev and the for loop moves it forward k times, stopping early if it falls off the end. If kth is null, fewer than k nodes remain, so we break. Otherwise groupNext = kth.next is the first node after the group.
Next comes the reversal. prev starts at groupNext, the line that keeps the back of the group tied on, and curr starts at groupPrev.next, the group's first node. The inner while loop runs until curr reaches groupNext, so it turns exactly k nodes, with the same four lines as plain reversal: save next, point curr back at prev, move prev, move curr.
Then we tie the front. oldFirst = groupPrev.next is saved first, because the next line overwrites it. groupPrev.next = kth makes the node before the group point to its new first node, and groupPrev = oldFirst moves our finger to the group's new last node, ready for the next round. When the loop ends, return dummy.next hands back the new head, which for our example is node 3.
7How much it costs, and the cases at the edges
Let us count on the example first. The walks to find kth took 3 steps, 3 steps and then 2 steps before finding null, 8 in all, and the reversal turned 6 nodes, so about 14 node visits for 7 nodes. In general each node is visited once by a walk and at most once by a reversal, so the time is about 2n steps, which is O(n).
The extra space is O(1), because the method keeps the same eight references however long the list and however large k is. The copying method needed O(n), a stack of k nodes needs O(k), and recursion per group needs one waiting call per group.
| Approach | Time | Extra space |
|---|---|---|
| Copy values, reverse blocks, write back (brute force) | O(n) | O(n) |
| Stack of k nodes per group | O(n) | O(k) |
| Recursion, one call per group | O(n) | O(n / k) call stack |
In place with groupPrev, kth and groupNext | O(n) | O(1) |
Only one edge case needs a line of its own, and we have met it: a k below 1 is refused with an exception at the top of the method. The others need no special code. With k = 1 every group is one node, and turning one node with prev starting at groupNext changes nothing, so [1 2 3] comes back as it was. When k is larger than the list, the first walk runs out of nodes, the loop breaks at once, and [1 2] is returned unchanged. An empty list gives kth null on the first walk, so we return dummy.next, which is null, and main prints [].
When the length is an exact multiple of k, as with six nodes and k = 3, the last group's groupNext is null, so its old first node ends up pointing to null, which correctly ends the list, giving [3 2 1 6 5 4]. With k = 2 on five nodes the pairs are swapped and the single 5 is left alone, giving [2 1 4 3 5].
8Follow-up questions
How would you also reverse a last group shorter than k?
Instead of stopping when the walk runs out of nodes, we reverse what is left: from groupPrev.next to the end with prev starting at null, then link groupPrev.next to the new first node and stop. For 1 to 8 with k = 3 the last group 7, 8 would become 8, 7. It stays O(n) time and O(1) space.
How does swapping nodes in pairs relate to this?
Swapping every two neighbouring nodes is exactly this problem with k = 2, so the same method solves it, as main shows with [2 1 4 3 5]. A dedicated version is shorter: with a dummy and a finger prev on the node before a pair, take first = prev.next and second = first.next, then set first.next = second.next, second.next = first and prev.next = second, and move prev to first. It is the same rule of tying both ends of a segment.
What does a recursive version look like?
We check that k nodes exist from head. If not, we return head unchanged. Otherwise we reverse those k nodes with the usual loop, prev starting at null, and the old head, now the group's last node, gets head.next = reverseKGroup(groupNext, k), which reverses everything after the group and returns its new first node. We return the group's new first node. It reads nicely, but it keeps one waiting call per group, O(n / k) stack space, so the loop is safer for very long lists.
9Conclusion
We reversed a linked list in groups of k by walking k steps to prove each group was full, reversing it with prev starting at the node after the group so its back stayed tied on, and then pointing the node before the group at its new first node. A dummy node gave the first group a node in front of it, and the whole method takes O(n) time and O(1) space. The clue to remember is a change to a segment of a list: put a finger on the node before it and the node after it, change the inside, then tie both ends back on.
Open with
Let me confirm the rules first: I reverse each full group of k nodes by changing links, a last group shorter than k stays as it is, and I return the new head.
Then, if they want more
Copying the values into an array and reversing blocks works in O(n), but it uses O(n) extra space and moves values instead of links. I will do it in place. I put a dummy node in front of the head and keep groupPrev, the node before the current group, starting on the dummy.
Each round I walk k steps from groupPrev to find kth, the group's last node; if I run out of nodes, I stop. groupNext is kth.next. Then I reverse the group with the usual prev, curr, next loop, but I start prev at groupNext instead of null, so the group's old first node ends up pointing to the next group.
After the loop I save oldFirst as groupPrev.next, set groupPrev.next to kth, and move groupPrev to oldFirst. Each node is visited about twice, so it is O(n) time and O(1) extra space. I would test k = 1, k larger than the list, a length that is a multiple of k, and an empty list.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 59 times in that collection. How it is counted
- Official documentation
- StringBuilder (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Reverse the nodes of a linked list in groups of k.": https://scrivio-interview-library.netlify.app/data-structures/solutions/reverse-the-nodes-of-a-linked-list-in-groups-of-k-213c83/