Given an integer array nums, transform it into a wiggle array where elements alternate between peaks and valleys in a strict pattern: nums[0] < nums[1] > nums[2] < nums[3] > nums[4] < nums[5]...

Think of it like creating a zigzag mountain range where each peak is higher than its neighboring valleys, and each valley is lower than its neighboring peaks. The pattern must be strictly alternating - no equal adjacent elements allowed!

Example: [1,5,1,1,6,4] โ†’ [1,6,1,5,1,4] creates the pattern: small < large > small < large > small < large

You're guaranteed that a valid wiggle arrangement always exists for the input array.

Input & Output

example_1.py โ€” Basic Wiggle Sort
$ Input: [1,5,1,1,6,4]
โ€บ Output: [1,6,1,5,1,4]
๐Ÿ’ก Note: The output follows the wiggle pattern: 1 < 6 > 1 < 5 > 1 < 4. Each element at even index is smaller than its neighbors, and each element at odd index is larger than its neighbors.
example_2.py โ€” Small Array
$ Input: [1,3,2]
โ€บ Output: [2,3,1]
๐Ÿ’ก Note: For a 3-element array, we need: small < large > small. So 2 < 3 > 1 satisfies the wiggle condition perfectly.
example_3.py โ€” Duplicate Elements
$ Input: [1,1,2,2,3,3]
โ€บ Output: [2,3,1,3,1,2]
๐Ÿ’ก Note: Even with duplicates, we can create a valid wiggle pattern by strategically placing elements: 2 < 3 > 1 < 3 > 1 < 2.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n! ร— n)

O(n!) to generate all permutations, O(n) to check each permutation

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for storing one permutation at a time during generation

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 5 ร— 104
  • 0 โ‰ค nums[i] โ‰ค 5000
  • You may assume the input array always has a valid answer
  • The array is modified in-place with O(1) extra memory for the optimal solution
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen