KatInterview

Flip Every Block of K Consecutive Values in a Sequence

Linked ListsAuto-graded · 21 test cases
MediumAuto-gradedLinked Listslinked-listin-placepointers

Last 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 k elements).
  • If the final block has fewer than k elements, 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 values list gives an empty list.
  • If k == 1, the output equals the input.
  • If k is larger than the number of elements, the output equals the input.
  • If k equals 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^5
  • k >= 1
  • Values are integers.
  • Aim for O(n) time and O(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.