/25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

Hard
Linked Lists65.5% acceptance

Given a singly linked list represented by its head node, reverse every contiguous group of k nodes in the list. If the number of nodes remaining at the end is less than k, leave them unchanged. Only the node connections may be changed; node values must not be altered. Return the head node of the modified list.

Example 1

Input: head = ListNode(10, ListNode(20, ListNode(30, ListNode(40, ListNode(50))))) group_size = 2

Output: [20, 10, 40, 30, 50]

Explanation: Reverse every 2 nodes: [10,20]->[20,10], [30,40]->[40,30], [50] unchanged.

Example 2

Input: head = ListNode(7, ListNode(8, ListNode(9, ListNode(10)))) group_size = 3

Output: [9, 8, 7, 10]

Explanation: Reverse first 3 nodes: [7,8,9]->[9,8,7], [10] unchanged.

Constraints

  • 1 <= group_size <= node_count <= 5000
  • 0 <= ListNode.val <= 1000
  • Input is a singly linked list; nodes must not be altered, only their connections
Python (current runtime)

Case 1

Input: head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6)))))) group_size = 4

Expected: [4, 3, 2, 1, 5, 6]

Case 2

Input: head = ListNode(100, ListNode(200, ListNode(300))) group_size = 1

Expected: [100, 200, 300]

Case 3

Input: head = ListNode(5, ListNode(6, ListNode(7, ListNode(8, ListNode(9, ListNode(10)))))) group_size = 6

Expected: [10, 9, 8, 7, 6, 5]