← DiffPush

Reverse k node in groups

DiffPush Tier Linked List · Hard Promblems of LL O(n) · O(1) iterative (O(n/k) recursion stack for the recursive form)

Flipping Pallets a Truckload at a Time

A freight yard stacks outbound pallets in a single chain and a re-sequencer flips them in fixed batches of k so the oldest pallet of each batch ends up nearest the dock gate. If the chain ends with a partial batch — fewer than k pallets left — that leftover tail ships in its original order. The re-sequencer must confirm a full batch exists before flipping, then splice the flipped batch back onto the results of the remaining chain.

Input: An array head of n node values and an integer k, the group size.

Output: The values of the list after every complete group of k nodes is reversed and spliced back in order.

Constraints

Examples

Example 1

Input: {"head":[1,2,3,4,5],"k":2}
Output: [2,1,4,3,5]
Two full batches flip to (2,1) and (4,3); the leftover single pallet 5 ships as-is.

Example 2

Input: {"head":[1,2,3,4,5],"k":3}
Output: [3,2,1,4,5]
The first batch of three flips to 3-2-1; the remaining pair 4-5 is a partial batch and stays untouched.

Solve this in your browser →

Also on LeetCode ↗