Problem 353154 · medium · Level 03 Linear Management & Searching

Zigzag Arrangement

sorting · wiggle order · checker

Rearrange the integers in nums into a zigzag order: a new list z (a permutation of nums) such that

z[0] <= z[1] >= z[2] <= z[3] >= z[4] ...

Any arrangement satisfying the pattern is accepted. Return a new list; do not modify the input.

Examples

Input:  nums = [7, 2, 9, 4, 8, 1]
Output: [1, 4, 2, 8, 7, 9]        (one of several valid answers)
Explanation: 1 <= 4 >= 2 <= 8 >= 7 <= 9.

Constraints

  • 0 <= len(nums) <= 5 * 10**4
  • Duplicates are allowed; equal neighbours satisfy both <= and >=.
  • One test calls checked_zigzag(nums), which runs your zigzag and returns its answer only if nums is unchanged afterwards (otherwise it returns None).
  • Target complexity: O(n log n) (an O(n) single pass also exists).

Goals

  • Produce an arrangement that satisfies an alternating inequality pattern
  • Use a sorted order as a stepping stone to a non-standard order
  • Accept that many outputs are valid and reason about correctness, not a single answer
Starting Python…