Flip Every Block of K Consecutive Values in a Sequence
Linked ListsAuto-graded · 21 test casesLast updated
Reverse each full consecutive block of k elements in a list of values, leaving a short trailing remainder untouched, using the pointer-based linked-list technique.
Block-wise Reversal
You are given a sequence of integers values, which represents the nodes of a singly linked list from front to back, and a positive integer k.
Split the sequence into consecutive blocks of exactly k elements, starting from the front: the first k elements form the first block, the next k elements form the second block, and so on.
- Reverse the order of the elements inside every full block (a block with exactly
kelements). - If the final block has fewer than
kelements, leave it exactly as it is. - The blocks themselves stay in their original order; only the elements inside each full block are reversed.
Return the resulting sequence as a new list. The input list must not be modified.
The task is modelled on linked lists: a well-regarded approach is to build a singly linked list from values, relink the nodes in place with O(1) extra pointers, and read the values back out. Any approach that returns the correct result is accepted.
Edge-case rules
- An empty
valueslist gives an empty list. - If
k == 1, the output equals the input. - If
kis larger than the number of elements, the output equals the input. - If
kequals the number of elements, the whole sequence is reversed. - If the length is an exact multiple of
k, every block is reversed and there is no leftover.
Constraints
0 <= len(values) <= 10^5k >= 1- Values are integers.
- Aim for
O(n)time andO(1)extra working space beyond the output (when using the pointer approach).
Examples
Example 1
Input: reverse_blocks_of_k([1, 2, 3, 4, 5, 6, 7], 3)
Output: [3, 2, 1, 6, 5, 4, 7]
Example 2
Input: reverse_blocks_of_k([1, 2, 3, 4, 5], 2)
Output: [2, 1, 4, 3, 5]
Example 3
Input: reverse_blocks_of_k([1, 2, 3], 4)
Output: [1, 2, 3]
Hints
Hint 1
Before changing any pointer, check that at least k nodes remain from your current position. If they do not, stop and leave the rest as is.
Hint 2
Keep a pointer to the node just before the current block, and start from a dummy node placed in front of the list so the first block needs no special handling.
Hint 3
When reversing a block with the three-pointer method, start the 'previous' pointer at the node right after the block instead of None; the block's new tail then links to the rest of the list automatically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the list one block at a time, keeping a pointer group_prev to the node just before the current block. A dummy node placed in front of the head means the first block is handled like every other block.
For each block:
- Look ahead. Starting at
group_prev, step forwardktimes to find the block's last node,kth. If the list ends beforeksteps, fewer thanknodes remain, so stop without touching anything. - Record the boundary.
group_next = kth.nextis the first node after the block. - Reverse in place. Use the usual three-pointer reversal, but start
prevatgroup_nextinstead ofNone. The block's old first node then points directly at the rest of the list, so no extra relinking is needed. Stop whencurrreachesgroup_next. - Stitch. The old first node (
group_prev.nextbefore the change) is now the block's tail. Setgroup_prev.next = kth(the new block head), then movegroup_prevto that old first node, which immediately precedes the next block.
Finally return dummy.next. The wrapper builds the linked list from the input values and reads the values back out, so the caller's list is never modified.
Why it is correct
At the start of each iteration, every node from the dummy through group_prev is in its final position, and group_prev.next begins the unprocessed suffix, which is still in its original order. The look-ahead happens before any mutation, so a short tail is never altered. When a full block exists, the reversal touches exactly the k nodes up to group_next, links the new tail to the untouched suffix (because prev started at group_next), and group_prev.next = kth links the finished prefix to the new head. The invariant therefore holds for the next block. The loop performs exactly floor(n / k) reversals and then exits.
Edge cases follow naturally: an empty list fails the look-ahead at once; k = 1 reverses single-node blocks (no change); k > n has no full block; k == n reverses everything.
Complexity
- Time: O(n). Each node is visited at most twice, once by the look-ahead and once by the reversal.
- Space: O(1) extra pointers for the relinking (the wrapper uses O(n) to convert to and from a list, which is needed only because the judge passes plain lists). The solution is iterative, so there is no recursion-depth concern at
n = 10^5.
Reference solution
from typing import List, Optional
class ListNode:
__slots__ = ("val", "next")
def __init__(self, val: int = 0, next: "Optional[ListNode]" = None):
self.val = val
self.next = next
def _reverse_in_groups(head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
group_prev = dummy
while True:
# Look ahead for the k-th node of the block.
kth = group_prev
for _ in range(k):
kth = kth.next
if kth is None:
return dummy.next
group_next = kth.next
# Reverse the block; the old first node ends up pointing at group_next.
prev, curr = group_next, group_prev.next
while curr is not group_next:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
# Reconnect the block to the finished prefix.
old_first = group_prev.next
group_prev.next = kth
group_prev = old_first
def reverse_blocks_of_k(values: List[int], k: int) -> List[int]:
dummy = ListNode()
tail = dummy
for v in values:
tail.next = ListNode(v)
tail = tail.next
head = _reverse_in_groups(dummy.next, k)
result: List[int] = []
while head is not None:
result.append(head.val)
head = head.next
return result