Ctrl K

Reversing a List in Blocks

Hard
You are given the head of a singly linked list, head, and a number size. Split the list into consecutive blocks of size nodes, starting from the front, and reverse the order of the nodes inside every full block. If fewer than size nodes are left at the end, leave that tail alone. You may not change the values stored in the nodes; rearrange the nodes themselves. Return the head of the resulting list. Try to use only O(1) extra memory.
Example 1
head=list_node([10, 20, 30, 40, 50, 60, 70, 80]), size=3 → [30, 20, 10, 60, 50, 40, 70, 80]

The blocks [10, 20, 30] and [40, 50, 60] are reversed; the tail [70, 80] is shorter than 3 and stays as it is.

Example 2
head=list_node([5, 6, 7, 8]), size=4 → [8, 7, 6, 5]

The whole list is a single block, so it is reversed entirely.

Example 3
head=list_node([1, 2, 3]), size=1 → [1, 2, 3]

A block of one node does not change when reversed.

Constraints
  • The list has n nodes
  • 1 ≤ size ≤ n ≤ 5000
  • 0 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsAdding Digit Lists MediumZip Two Sorted Chains EasyTrade Places in Twos MediumList Folded From Both Ends MediumCut Out Matching Nodes Easy
loading Python…
Input
head=list_node([10, 20, 30, 40, 50, 60, 70, 80]), size=3
Expected
[30, 20, 10, 60, 50, 40, 70, 80]

Run checks the first 3 tests in your browser. Submit checks all 108 tests on the server, hidden ones included.