#25

Reverse Nodes in k-Group

Hard Group reversal with reconnection

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Reverse the nodes of a linked list k at a time. A final group with fewer than k nodes stays as is. Only O(1) extra memory.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: reverse every block of k nodes; leave a short last block alone.

Why this works: check k nodes exist, reverse that block, reconnect it to the previous block, move on.

Example: 1→2→3→4→5, k = 2

[2,1] [4,3] [5]2→1→4→3→5

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Reversing the last short group too.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Linked List
🎬 Episodes 40–45: video coming soon