Imagine you're creating a mountain range pattern with numbers! Given an integer array nums, your task is to rearrange the elements to create a "wiggle" pattern where elements alternate between smaller-or-equal and greater-or-equal relationships.
Specifically, reorder the array so that: nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3] ≥ nums[4]...
The pattern: Each element at an even index should be ≤ its right neighbor, and each element at an odd index should be ≥ its right neighbor. Think of it as creating peaks and valleys!
Input: An integer array with at least one element
Output: The same array rearranged in wiggle sort order
Guarantee: A valid wiggle arrangement always exists for the input.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array, checking and potentially swapping each adjacent pair once
Only using a constant amount of extra space for the swapping operation
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- 0 ≤ nums[i] ≤ 5000
- The input array always has a valid wiggle sort arrangement