Reverse Nodes in k-Group

Linked Lists, problem 8 of 8

Reverse Nodes in k-Group

Hard

LC #25

in-place reversaldummy head

Not attempted yet

Given the head of a linked list and a positive integer k, reverse the nodes in each consecutive block of k and return the new head. If the last block has fewer than k nodes, leave it as it is.

Rearrange the nodes themselves, not their values.

Example 1

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2

Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

Example 3

Input: head = [1,2,3,4,5,6], k = 3
Output: [3,2,1,6,5,4]

Constraints

  • 1 ≤ k ≤ number of nodes ≤ 3 · 10⁴
  • 0 ≤ Node.val ≤ 10⁵

Can you do it with O(1) extra space?

Python

Loading draft…

Test results

9 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 6 hidden

Run examples, then submit all tests.