DSA AnimatorREVISION VIDEOS
← Back to problems
New

Reverse Nodes in K-Group — LeetCode 25 video explanation

Reverse the nodes of the list k at a time. If fewer than k nodes remain at the end, leave them as they are.

Loading videos…

DSA Animator › DSA Revision › Linked List › Reverse Nodes in K-Group

Key moments in the Reverse Nodes in K-Group video

0:04Problem0:10Example0:17Brute force0:24Key idea0:34Dry run0:47Code1:00Takeaway

What you will learn

Remember: count k, reverse k, reconnect, repeat. A short tail stays untouched. The video solves Reverse Nodes in K-Group (LeetCode 25, Hard) with the Pointer Reversal pattern from the Linked List topic, and you can replay every step in the interactive Reverse Nodes in K-Group animation.

Reverse Nodes in K-Group video transcript

Problem

Reverse the nodes of the list k at a time. If fewer than k nodes remain at the end, leave them as they are.

Example

For 1, 2, 3, 4, 5 with k equal to 2, the result is 2, 1, 4, 3, 5.

Brute force

Copying groups into arrays and rewriting values uses extra space. We can reverse each group in place.

Key idea

Keep a pointer to the node before the current group. Check that k nodes exist ahead, and stop if they do not. Reverse those k nodes, connect them back, and jump to the end of the group.

Dry run

The first group is 1 and 2, which becomes 2, 1. The next group is 3 and 4, which becomes 4, 3. Only 5 is left, fewer than k, so it stays. The result is 2, 1, 4, 3, 5.

Code

In code, start with a dummy, and group previous at the dummy. Find the k-th node, and stop if it is null. Reverse the group with the standard loop, then reconnect its head and tail. It's O of n time and O of 1 space.

Takeaway

Remember: count k, reverse k, reconnect, repeat. A short tail stays untouched.

More Linked List revision videos

← All 185 DSA revision videos