Reverse nodes in even-length linked-list groups
Company: TikTok
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates proficiency with singly linked list manipulation, in-place group operations (including conditional group reversal based on group length), pointer handling, and reasoning about linear time and constant extra space constraints.
Constraints
- 1 <= n <= 10^5 (n = number of nodes); the test harness additionally allows the empty list for completeness.
- Node values can be any integers (including negatives); values do not affect the grouping/reversal logic.
- Target O(n) time and O(1) extra space (excluding any recursion stack).
Examples
Input: ([1, 2, 3, 4, 5, 6, 7, 8, 9],)
Expected Output: [1, 3, 2, 4, 5, 6, 7, 8, 9]
Explanation: Groups [1] | [2,3] | [4,5,6] | [7,8,9]. Only [2,3] is even (len 2) -> reversed to [3,2]. Last group length 3 is odd -> unchanged.
Input: ([5, 2, 6, 3, 9, 1, 7, 3, 8, 4],)
Expected Output: [5, 6, 2, 3, 9, 1, 4, 8, 3, 7]
Explanation: Groups [5] | [2,6] | [3,9,1] | [7,3,8,4]. [2,6] (len 2) -> [6,2]; [7,3,8,4] (len 4) -> [4,8,3,7]; odd groups unchanged.
Hints
- Track the last node of the previously finalized group with a `prev` pointer (start with a dummy head). For each group, first walk forward up to `group_size` nodes to measure the group's ACTUAL length — it may be shorter than `group_size` for the final group.
- Only the actual length matters for parity. If it's even, reverse exactly that many nodes; if odd, just advance `prev` past them.
- When reversing a sublist of length `count`, point the reversed nodes so the group's new last node connects to the first node AFTER the group. After reversing, the original first node of the group becomes the group's tail — set `prev` to it before incrementing `group_size`.