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^40 ≤ nums[i] ≤ 5000See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI