Last updated on February 9th, 2025 at 07:26 am
Here, we see a Wiggle Sort II LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Sort
Companies
Level of Question
Medium

Wiggle Sort II LeetCode Solution
Table of Contents
1. Problem Statement
Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….
You may assume the input array always has a valid answer.
Example 1:
Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.
Example 2:
Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]
2. Coding Pattern Used in Solution
The coding pattern used in all the provided implementations is “Sorting and Index Manipulation”, a common approach in problems where the goal is to rearrange elements in a specific order based on their sorted positions. The idea is to sort the array and then rearrange elements into a “wiggle” pattern, where elements alternate between smaller and larger values.
3. Code Implementation in Different Languages
3.1 Wiggle Sort II C++
class Solution { public: void wiggleSort(vector<int>& nums) { vector<int> sorted(nums); sort(sorted.begin(), sorted.end()); for (int i=nums.size()-1, j=0, k=i/2+1; i>=0; i--) nums[i] = sorted[i&1 ? k++ : j++]; } };
3.2 Wiggle Sort II Java
class Solution { public void wiggleSort(int[] nums) { int n=nums.length-1; int[] newarr=Arrays.copyOf(nums,nums.length); Arrays.sort(newarr); for(int i=1;i<nums.length;i+=2) nums[i]=newarr[n--]; for(int i=0;i<nums.length;i+=2) nums[i]=newarr[n--]; } }
3.3 Wiggle Sort II JavaScript
var wiggleSort = function(nums) { nums.sort((b,a)=>b-a); let mid = Math.floor(nums.length/2) mid+=nums.length%2==0?0:1; let even = nums.slice(0, mid); let odd = nums.slice(mid); for(let i=0;i<nums.length;i++) { if (i%2==0) { nums[i] = even.pop(); } else { nums[i] = odd.pop(); } } };
3.4 Wiggle Sort II Python
class Solution(object): def wiggleSort(self, nums): nums.sort() half = len(nums[::2]) nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n log n) | O(n) |
Java | O(n log n) | O(n) |
JavaScript | O(n log n) | O(n) |
Python | O(n log n) | O(n) |