Dashboard
LC #25

Reverse Nodes in k-Group

Pattern · ?GoogleAmazonMetaMicrosoft

Problem

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

Constraints

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

Example

Input
head = [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)

Spot the pattern

Which pattern cracks it?

Hints

One at a time
Solve on LeetCode ↗