Reverse Nodes in k-Group - Problem

Imagine you have a linked list that you need to reverse in groups of k nodes at a time. This is like organizing a line of people into groups and having each group face the opposite direction!

Given the head of a linked list, your task is to:

  • Reverse the nodes of the list k at a time
  • Return the modified list
  • Important: If the remaining nodes are fewer than k, leave them as they are
  • You can only rearrange the node pointers - no changing values!

Example: If you have list 1→2→3→4→5 and k=3, you get 3→2→1→4→5 (first 3 nodes reversed, last 2 unchanged)

Input & Output

example_1.py — Basic Group Reversal
$ Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
💡 Note: We have two complete groups of 2 nodes each: (1,2) becomes (2,1), (3,4) becomes (4,3), and the remaining node 5 stays as is.
example_2.py — Larger Groups
$ Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
💡 Note: Only one complete group of 3 nodes: (1,2,3) becomes (3,2,1). The remaining 2 nodes (4,5) are fewer than k=3, so they remain unchanged.
example_3.py — Edge Case
$ Input: head = [1], k = 1
Output: [1]
💡 Note: With k=1, each group has only 1 node, so reversing doesn't change anything. The list remains [1].

Constraints

  • The number of nodes in the list is n
  • 1 ≤ k ≤ n ≤ 5000
  • 0 ≤ Node.val ≤ 1000
  • Follow-up: Can you solve the problem in O(1) extra memory space?

Visualization

Tap to expand
🏭 Assembly Line Reorganization (k=3)Before: Workers in Line👷1👷2👷3👷4👷5Team of k=3Process: Reverse Complete TeamReverse DirectionAfter: Reorganized Line👷3👷2👷1👷4👷5Reversed TeamIncomplete Team (Unchanged)💡 Key Insights1. Complete Teams OnlyOnly reverse when we have exactly k workers2. Maintain ConnectionsKeep the assembly line connected throughout3. In-Place OperationNo additional assembly lines needed4. EfficiencyEach worker moved exactly once: O(n)ReversedUnchanged
Understanding the Visualization
1
Identify Team Size
Count k workers to form a complete team
2
Reverse Team Direction
Have each complete team face the opposite direction
3
Maintain Line Connection
Ensure teams remain connected in the assembly line
4
Handle Incomplete Team
Leave remaining workers (< k) in original direction
Key Takeaway
🎯 Key Insight: Process the linked list systematically by identifying complete groups of k nodes, reversing each group in-place through pointer manipulation, and maintaining proper connections between groups for an optimal O(n) time, O(1) space solution.
Asked in
Meta 45 Amazon 38 Microsoft 32 Google 28
89.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen