Skip to content
Decoder

Reverse Nodes in k-Group

Hard

Problem

You get the head of a linked list and a number k. Reverse the nodes `k` at a time: the first k nodes flip, then the next k, and so on. If fewer than k nodes are left at the end, leave them as they are. Relink the nodes themselves rather than swapping values, and return the new head.

Example 1

Input
1
Output
2 -> 3 -> 4 -> 5, k = 2 → 2 -> 1 -> 4 -> 3 -> 5

Example 2

Input
1
Output
2 -> 3 -> 4 -> 5, k = 3 → 3 -> 2 -> 1 -> 4 -> 5

Example 3

Input
1
Output
2 -> 3 -> 4 -> 5, k = 1 → 1 -> 2 -> 3 -> 4 -> 5

Try to use only O(1) extra memory.

Constraints

  • 1 <= k <= number of nodes <= 5000
  • 0 <= Node.val <= 1000

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.