Reverse a linked list in groups of k
Coding problemHardAsked in: Adobe, Amazon, Goldman Sachs, Microsoft, Paytm, Walmart
Given the head of a linked list and a whole number k, reverse the nodes in groups of k: the first k nodes are reversed, then the next k, and so on. If fewer than k nodes are left at the end, they stay in their original order. Return the new head.
Change the links between nodes; do not only swap the values. If k is 1, or larger than the number of nodes, the list does not change.
Examples
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]
Only two nodes are left after the first group, so they stay as they are.
Example 3
Input: head = [1,2], k = 3
Output: [1,2]
Constraints
- The list has between 0 and 100,000 nodes
- 1 <= k <= 100,000
- Each value is a 32-bit integer
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.