algorythms
In-place List Reversal
LC #25Hard

Reverse Nodes in k-Group

In-place List Reversal
GoogleAmazonMetaMicrosoft

Problem

Reverse the nodes of a linked list k at a time. If remaining nodes are fewer than k, leave them as is.

linked-listrecursion

Constraints

  • 1 ≤ n ≤ 5000
  • 0 ≤ Node.val ≤ 1000
  • 1 ≤ k ≤ n
  • If remaining nodes < k, leave them as-is

Example

Inputhead = [1, 2, 3, 4, 5], k = 2
Output[2, 1, 4, 3, 5]
Why

Groups: [1,2] → [2,1], [3,4] → [4,3], [5] left as-is (< k nodes)

Hints — reveal one at a time