Reverse Nodes in k-Group
You're given the head of a linked list and an integer k. Walk through the list in chunks of k consecutive nodes and reverse each chunk. If the nodes left over at the end number fewer than k, leave that final group in its original order.
Input Format
Implement reverseKGroup(head, k). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 ยท Run Sample
Input
head = [1,2,3,4,5]
k = 2 Output
[2,1,4,3,5] Example 2
Input
head = [1]
k = 1 Output
[1] Constraints
- 1 <= n <= 5000
- 0 <= Node.val <= 1000
- 1 <= k <= n
Test Cases (2)
Case 1
Args: [[1,2,3,4,5],2]
Expected: [2,1,4,3,5]
Case 2
Args: [[1],1]
Expected: [1]
Topics
Iterative K-Group Reversal
function reverseKGroup(head, k) {
const dummy = {next: head};
let prev = dummy;
while (true) {
let kth = prev;
for (let i = 0; i < k; i++) { kth = kth.next; if (!kth) return dummy.next; }
let curr = prev.next, next = curr.next;
for (let i = 0; i < k - 1; i++) {
curr.next = next.next; next.next = prev.next; prev.next = next; next = curr.next;
}
prev = curr;
}
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.