KatInterview

Flatten a Linked List in K-Group Level Order

Linked ListsAuto-graded · 17 test cases
EasyAuto-gradedLinked Listslinked listsk-group operationspointer manipulation

Last updated

Tests pointer manipulation by collecting nodes from a singly linked list in chunks of k, then reversing the order within each chunk's values to produce a flat list.

Flatten a Linked List in K-Group Level Order

You are given a singly linked list represented as a Python list of integers (where lst[i] is the value of the i-th node, starting from the head), and a positive integer k.

Your task is to process the list in non-overlapping groups of k consecutive nodes, and for each group, reverse the values within that group before collecting them. Remaining nodes at the end that do not fill a complete group of k are kept in their original order (not reversed).

Return a single flat list of integers containing all values in the processed order.

Details

  • Process groups left-to-right.
  • Within each complete group of exactly k nodes, output the values in reversed order.
  • If the remaining tail has fewer than k nodes, output those values in their original order.
  • An empty input list returns an empty list.

Constraints

  • 1 ≤ k ≤ 1000
  • 0 ≤ len(lst) ≤ 2000
  • -10^6 ≤ lst[i] ≤ 10^6

Examples

Example 1

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

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

Example 2

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

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

Example 3

Input: flatten_k_group_reversed([], 4)

Output: []

Hints

Hint 1

Split the list into chunks of size k — the last chunk may be smaller than k.

Hint 2

Reverse each chunk that has exactly k elements; leave shorter tail chunks untouched.

Hint 3

Concatenate the processed chunks in order to build the final result.