MediumArraysSortingDivide and Conquer

1 approach, code in every language

Problem description

Reorder an integer array in place so its values alternate in a strict zig-zag: the element at every odd index must be strictly larger than its neighbors, giving the pattern nums[0] < nums[1] > nums[2] < nums[3] and so on.

The input is guaranteed to permit at least one valid arrangement, and if several are possible any of them is acceptable.

Example 1

Input: nums = [1,5,1,1,6,4]

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

Each peak sits at an odd index and exceeds both neighbors; other valid answers also exist.

Example 2

Input: nums = [1,3,2,2,3,1]

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

Constraints

  • 1 ≤ nums.length ≤ 5 * 10^4
  • 0 ≤ nums[i] ≤ 5000

After the pattern

Now solve one you haven't seen.

Laying the Readings Out in a Zigzag is our own problem on the technique behind Wiggle Sort II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free