KatInterview

Flip Every Complete Block of K in a Sequence

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked-listin-place-reversaltwo-pointers

Last updated

Reverse each full consecutive block of k items in a list, leaving a shorter leftover tail unchanged; tests pointer-style reversal logic and boundary handling.

Flip Every Complete Block of K

You are given a sequence of integers, values, that represents a singly linked list from head to tail, and a positive integer k.

Split the sequence from the front into consecutive blocks of exactly k elements. Reverse the order of the elements inside every complete block. If the final block has fewer than k elements, leave it exactly as it appears in the input.

Return the resulting sequence as a new list. Do not modify the input list.

The problem is modeled on a linked list, where only the links between nodes may be rearranged and not the stored values. Your function receives and returns plain Python lists, but a strong solution should be able to handle the reversal at the pointer level.

Rules

  • Blocks are formed starting from the first element, with no overlap and no gaps.
  • Only blocks containing exactly k elements are reversed.
  • Elements of a leftover shorter block keep their original order and position.
  • If k = 1, the output equals the input.
  • If k is larger than the length of the list, the output equals the input.

Constraints

  • 1 <= k <= n <= 5000, where n is the length of values.
  • 0 <= values[i] <= 1000.

Examples

Example 1

Input: flip_k_blocks([1, 2, 3, 4, 5], 2)

Output: [2, 1, 4, 3, 5]

Example 2

Input: flip_k_blocks([1, 2, 3, 4, 5], 3)

Output: [3, 2, 1, 4, 5]

Hints

Hint 1

Before reversing a block, check that at least k elements remain from the current position. If fewer remain, stop and keep the rest unchanged.

Hint 2

In a linked list, a dummy node placed before the head removes the special case where the first block changes the head. Track the node just before the current block, the block's last node, and the node just after it.

Hint 3

Reverse a block in place with the usual prev/curr walk, but start prev at the node after the block so the block's new tail is already connected to the rest. Then attach the block's new front to the node before it and move on.