KatInterview

Reorder Linked List by Zigzag Level Buckets

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked listsarray manipulationreordering

Last updated

Tests pointer-manipulation intuition by reordering a singly-linked list (given as an array) into a zigzag pattern based on partitioning nodes into fixed-size buckets.

Reorder Linked List by Zigzag Level Buckets

You are given a singly-linked list represented as a plain Python list nodes (each element is the node's integer value, in order from head to tail), and a positive integer k.

Task

Partition the list into consecutive buckets of size k. The last bucket may contain fewer than k elements if the list length is not divisible by k.

Reorder the list as follows:

  1. Number the buckets 0, 1, 2, … from left to right.
  2. Keep the nodes within each bucket in their original relative order.
  3. Arrange the buckets in a zigzag order:
    • Bucket 0 → forward (first)
    • Bucket 1 → reversed (appended in reverse bucket order — see below)
    • Bucket 2 → forward
    • Bucket 3 → reversed
    • …and so on (even-indexed buckets forward, odd-indexed buckets reversed).

"Reversed bucket order" means the bucket as a whole moves to a later position in the output — it does not reverse the nodes inside the bucket. All even-indexed buckets appear first (in their original bucket order), followed by all odd-indexed buckets (in reverse bucket order).

More precisely, the output is:

[bucket 0] [bucket 2] [bucket 4] ... [last odd bucket] ... [bucket 3] [bucket 1]

That is:

  • Even-indexed buckets in increasing index order: bucket 0, bucket 2, bucket 4, …
  • Odd-indexed buckets in decreasing index order: …, bucket 5, bucket 3, bucket 1

The values inside each bucket are always kept in their original order.

Return the reordered list as a plain Python list.

Constraints

  • 1 ≤ len(nodes) ≤ 2000
  • 1 ≤ k ≤ len(nodes)
  • -10^6 ≤ nodes[i] ≤ 10^6
  • If nodes is empty, return [].
  • If there is only one bucket (i.e. k ≥ len(nodes)), return nodes unchanged.

Examples

Example 1

Input: zigzag_bucket_reorder([1, 2, 3, 4, 5, 6, 7, 8], 2)

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

Example 2

Input: zigzag_bucket_reorder([10, 20, 30, 40, 50], 3)

Output: [10, 20, 30, 40, 50]

Example 3

Input: zigzag_bucket_reorder([7], 1)

Output: [7]

Hints

Hint 1

First, split the list into consecutive chunks of size k — a simple loop with slicing works well here.

Hint 2

Separate the chunks by index parity: collect even-indexed chunks in one list and odd-indexed chunks in another.

Hint 3

Concatenate: even-indexed chunks in order, then odd-indexed chunks in reverse order; flatten the result.