Reverse a Linked List in Groups of K
Updated
Problem statement
head points to the start of a one-way linked list, and k is a whole number, at least 1. Starting from head, cut the list into back-to-back groups of k nodes. Flip the order of the nodes inside each full group, keep the groups in their original order, and return the node that now starts the list.
When the length cannot be split evenly into groups of k, the final group is shorter than k. Do not change the order of that final group.
Function
reverseKGroup(head: ListNode, k: int) → ListNodeExamples
Example 1
head = [10,20,30,40,50,60,70,80]k = 3return = [30,20,10,60,50,40,70,80]The first two groups of 3 are 10, 20, 30 and 40, 50, 60. Each is reversed, giving 30, 20, 10 and 60, 50, 40. The last group, 70, 80, has only 2 nodes, fewer than 3, so it stays as it is.
Example 2
head = [5,1,8,2]k = 2return = [1,5,2,8]The 4 nodes split into two full groups of 2: 5, 1 and 8, 2. Reversing each gives 1, 5 and 2, 8. Nothing is left over.
Example 3
head = [6,-2,3]k = 3return = [3,-2,6]k equals the length of the list, so the whole list is one group and is reversed.
Constraints
1 <= n <= 1000, wherenis the number of nodes.1 <= k <= n- Every node value is between
-1000and1000. - Values may repeat.
More Expedia Onsite Interview questions
- Scramble StringONSITE INTERVIEW · Seen Sep 2026
- Smallest Sufficient TeamONSITE INTERVIEW · Seen Sep 2026
- Check Anagram Pairs Index by IndexONSITE INTERVIEW · Seen Oct 2025
- Fresh Oranges Left After Rotting StopsONSITE INTERVIEW · Seen Oct 2025
- Longest Increasing SubsequenceONSITE INTERVIEW · Seen Oct 2025
- Lowest Common Ancestor with Repeated and Missing ValuesONSITE INTERVIEW · Seen Oct 2025
- Shortest Substring with Exactly K OnesONSITE INTERVIEW · Seen Oct 2025
- Middle Element of a Linked ListONSITE INTERVIEW · Seen Nov 2024
- Minimum in a Rotated Sorted ArrayONSITE INTERVIEW · Seen Sep 2024
- Mirror Image Binary TreesONSITE INTERVIEW · Seen Sep 2024
Similar questions at other companies
- Reverse Nodes in K-GroupAmazon · ONSITE INTERVIEW
- Merge K Sorted Linked ListsThe Walt Disney Company · OA · ONSITE INTERVIEWThe Walt Disney Company interview questions
- Merge K Sorted ListsBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Reverse Nodes in k-GroupMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Merge K Sorted ListsSkydio · ONSITE INTERVIEWSkydio interview questions
- Merge K Sorted Linked Lists Into OneCapital One · ONSITE INTERVIEWCapital One interview questions
- Sorted Doubly Linked List to Balanced BST In PlaceSalesforce · ONSITE INTERVIEWSalesforce interview questions
- Merge K Sorted Linked ListsBharatPe · PHONE SCREEN
- Reverse Nodes in K-GroupByteDance · PHONE SCREENByteDance interview questions
- Reverse a Linked ListCisco · PHONE SCREENCisco interview questions