Reverse Nodes in Groups of K
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to manipulate linked list pointers in place, handling in-group reversal while preserving overall structure. It tests practical application of data structure manipulation and edge-case handling, a common coding and algorithms interview topic assessing pointer-rewiring skill and space-efficient thinking.
Constraints
- 1 <= n <= 5 * 10^4 where n is the number of nodes
- 1 <= k <= n
- Each node value fits in a 32-bit signed integer
- Target O(n) time
- Only rewire links; a full group of k is reversed, a trailing partial group of size < k is left in original order
Examples
Input: ([1, 2, 3, 4, 5], 2)
Expected Output: [2, 1, 4, 3, 5]
Explanation: Pairs (1,2) and (3,4) are each reversed; the final node 5 is alone (fewer than k left) so it stays in place.
Input: ([1, 2, 3, 4, 5], 3)
Expected Output: [3, 2, 1, 4, 5]
Explanation: The first three nodes are reversed; the trailing 4->5 is a partial group of size 2 (< 3) and is left untouched.
Input: ([1, 2, 3, 4, 5], 1)
Expected Output: [1, 2, 3, 4, 5]
Explanation: k = 1 reverses groups of one node, which leaves the list unchanged.
Input: ([1], 1)
Expected Output: [1]
Explanation: A single-node list is returned unchanged.
Input: ([1, 2, 3, 4, 5, 6], 3)
Expected Output: [3, 2, 1, 6, 5, 4]
Explanation: Two full groups of three; both are reversed and there is no partial tail.
Input: ([1, 2, 3, 4], 4)
Expected Output: [4, 3, 2, 1]
Explanation: k equals n, so the entire list is one full group and is fully reversed.
Input: ([-1, -2, -3, 100, 5], 2)
Expected Output: [-2, -1, 100, -3, 5]
Explanation: Negative and large values reverse correctly in pairs: (-1,-2) and (-3,100); trailing 5 stays.
Hints
- Before reversing a group, first confirm there are at least k nodes remaining; if fewer than k remain, leave them as-is.
- Reverse exactly k pointers at a time using the standard prev/cur/next three-pointer swap, then connect the reversed group's new tail to the result of processing the rest of the list.
- Recursion cleanly handles the 'connect to the next group' step: reverse_k returns the new head of everything from this group onward. For O(1) space, do it iteratively with a group-previous pointer that stitches each reversed block back in.