/25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

Hard
Linked Lists65.5% acceptance

Given the head node of a singly linked list and an integer group_size, reverse the nodes of the list in contiguous groups of group_size. If the number of nodes is not a multiple of group_size, leave the remaining nodes at the end unchanged. Only the node connections may be changed; node values must not be altered. Return the head node of the modified linked 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: Nodes are reversed in groups of 2: [10,20]->[20,10], [30,40]->[40,30], [50] remains unchanged.

Example 2

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

Output: [9, 8, 7, 10]

Explanation: First 3 nodes reversed: [7,8,9]->[9,8,7], [10] remains unchanged.

Constraints

  • 1 <= group_size <= n <= 5000, where n is the number of nodes in the list
  • 0 <= ListNode.val <= 1000
  • The input list is singly linked
  • Node values must not be altered; only node connections may be changed
Python (current runtime)

Case 1

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

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

Case 2

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

Expected: [1, 2, 3]

Case 3

Input: head = ListNode(100) group_size = 1

Expected: [100]

Case 4

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

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