Reverse Nodes in K-Sized Groups
Company: Bytedance
Role: Software Engineer
Category: Coding & Algorithms
Interview Round: Technical Screen
Quick Answer: This question evaluates skills in manipulating singly linked lists, pointer reassignments, and performing in-place group transformations while meeting time and space complexity constraints.
Constraints
- 0 <= len(values) <= 100000
- 1 <= k <= 100000
- -1000000000 <= values[i] <= 1000000000
Examples
Input: ([1,2,3,4,5], 2)
Expected Output: [2,1,4,3,5]
Explanation: The list is reversed in pairs: (1,2) becomes (2,1), (3,4) becomes (4,3), and 5 remains as is.
Input: ([1,2,3,4,5], 3)
Expected Output: [3,2,1,4,5]
Explanation: The first three nodes form a complete group and are reversed. The last two nodes are fewer than k, so they stay unchanged.
Input: ([1,2], 3)
Expected Output: [1,2]
Explanation: There are fewer than 3 nodes total, so no reversal happens.
Input: ([], 4)
Expected Output: []
Explanation: An empty list remains empty.
Input: ([7], 1)
Expected Output: [7]
Explanation: Groups of size 1 do not change the list.
Input: ([-1,-1,2,3,4,5], 4)
Expected Output: [3,2,-1,-1,4,5]
Explanation: The first four nodes are reversed as one group. The remaining two nodes are left unchanged.
Hints
- Use a dummy node so reconnecting the previous part of the list to a reversed group is easier.
- Before reversing a group, first check whether there are at least k nodes remaining.