324. Wiggle Sort II
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to reorder an array nums to follow a "wiggle" pattern: nums[0] nums[2] < nums[3].... This means every element at an odd index must be greater than its neighbors, and every element at an even index must be smaller than its neighbors.
Solution
Wiggle Sort II in Python
class Solution:
def wiggleSort(self, nums: list[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if n <= 1:
return
# Step 1: Find the median using a Quickselect-like algorithm.
# The median is the (n/2)-th element.
mid_idx = n // 2
# In-place quickselect to find the median element.
# After this, nums[mid_idx] will be the median, with smaller elements
# potentially on its right and larger on its left (not fully sorted).
# We need a copy because our quickselect modifies the list, but we need the original order for partitioning.
temp_nums = list(nums)
def find_kth_smallest(arr, k):
left, right = 0, len(arr) - 1
while left <= right:
# A simple partition scheme. A random pivot would be better for performance guarantee.
pivot_idx = (left + right) // 2
arr[pivot_idx], arr[right] = arr[right], arr[pivot_idx]
store_idx = left
for i in range(left, right):
if arr[i] < arr[right]:
arr[i], arr[store_idx] = arr[store_idx], arr[i]
store_idx += 1
arr[right], arr[store_idx] = arr[store_idx], arr[right]
if store_idx == k:
return arr[k]
elif store_idx < k:
left = store_idx + 1
else:
right = store_idx - 1
return arr[left]
median = find_kth_smallest(temp_nums, mid_idx)
# Step 2: 3-way partition using virtual indexing.
# This maps virtual indices to physical wiggle-sorted indices.
# A(i) = (1 + 2*i) % (n | 1)
def A(i):
return (1 + 2 * i) % (n | 1)
left, i, right = 0, 0, n - 1
while i <= right:
mapped_i = A(i)
if nums[mapped_i] > median:
mapped_left = A(left)
nums[mapped_left], nums[mapped_i] = nums[mapped_i], nums[mapped_left]
left += 1
i += 1
elif nums[mapped_i] < median:
mapped_right = A(right)
nums[mapped_right], nums[mapped_i] = nums[mapped_i], nums[mapped_right]
right -= 1
else: # nums[A(i)] == median
i += 1
Wiggle Sort II in Java
class Solution {
public void wiggleSort(int[] nums) {
int n = nums.length;
if (n <= 1) {
return;
}
// Step 1: Find the median. This is O(n) on average.
int median = findKthLargest(nums, (n + 1) / 2);
// Step 2: 3-way partition using virtual indexing.
int left = 0, i = 0, right = n - 1;
while (i <= right) {
int mapped_i = newIndex(i, n);
if (nums[mapped_i] > median) {
int mapped_left = newIndex(left, n);
swap(nums, mapped_left, mapped_i);
left++;
i++;
} else if (nums[mapped_i] < median) {
int mapped_right = newIndex(right, n);
swap(nums, mapped_right, mapped_i);
right--;
} else {
i++;
}
}
}
// Helper for virtual indexing
private int newIndex(int index, int n) {
return (1 + 2 * index) % (n | 1);
}
// Helper to find the k-th largest element (which is n-k+1 smallest)
private int findKthLargest(int[] nums, int k) {
// We are looking for the k-th smallest element, which is the median.
// In a 0-indexed array, this is the element at index k-1.
int targetIndex = k - 1;
int left = 0, right = nums.length - 1;
while (left < right) {
int pivotIndex = partition(nums, left, right);
if (pivotIndex == targetIndex) {
break;
} else if (pivotIndex < targetIndex) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return nums[targetIndex];
}
// Lomuto partition scheme for Quickselect
private int partition(int[] nums, int left, int right) {
int pivot = nums[right];
int i = left;
for (int j = left; j < right; j++) {
if (nums[j] <= pivot) {
swap(nums, i, j);
i++;
}
}
swap(nums, i, right);
return i;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
Wiggle Sort II in C++
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int n = nums.size();
if (n <= 1) {
return;
}
// Step 1: Find the median in O(n) average time.
// nth_element partitions the array such that the element at the given
// position (nums.begin() + n/2) is the element that would be in that
// position in a sorted array. All elements before it are less than or equal to it.
auto mid_ptr = nums.begin() + n / 2;
nth_element(nums.begin(), mid_ptr, nums.end());
int median = *mid_ptr;
// Step 2: 3-way partition using virtual indexing.
// The mapping `A(i)` maps indices 0, 1, 2, ... to their target wiggle-sorted positions.
// A(i) = (1 + 2*i) % (n | 1) maps:
// - First half of indices to odd positions (1, 3, 5, ...)
// - Second half of indices to even positions (0, 2, 4, ...)
// This way, we can place larger numbers (which should be at odd indices)
// at the beginning of our virtual array.
#define A(i) nums[(1 + 2 * (i)) % (n | 1)]
int left = 0, i = 0, right = n - 1;
// `left` tracks the boundary for elements > median
// `i` is the current element to inspect
// `right` tracks the boundary for elements < median
while (i <= right) {
if (A(i) > median) {
// Found an element larger than median.
// It belongs to the 'left' side of the virtual array (large numbers).
// Swap it with the element at the `left` boundary.
swap(A(left), A(i));
left++;
i++;
} else if (A(i) < median) {
// Found an element smaller than median.
// It belongs to the 'right' side of the virtual array (small numbers).
// Swap it with the element at the `right` boundary.
swap(A(right), A(i));
right--;
// We don't increment `i` because the new element at A(i) needs to be checked.
} else { // A(i) == median
// Element is a median, which is in its correct partition. Move on.
i++;
}
}
}
};
Wiggle Sort II in TypeScript
/**
Do not return anything, modify nums in-place instead.
*/
function wiggleSort(nums: number[]): void {
const n = nums.length;
if (n <= 1) {
return;
}
// Helper for virtual indexing: (1 + 2*i) % (n | 1)
const mapIndex = (i: number): number => (1 + 2 * i) % (n | 1);
// Helper to swap elements
const swap = (i: number, j: number): void => {
[nums[i], nums[j]] = [nums[j], nums[i]];
};
// Helper for partitioning in quickselect
const partition = (arr: number[], left: number, right: number): number => {
const pivotValue = arr[right];
let i = left;
for (let j = left; j < right; j++) {
if (arr[j] <= pivotValue) {
[arr[i], arr[j]] = [arr[j], arr[i]];
i++;
}
}
[arr[i], arr[right]] = [arr[right], arr[i]];
return i;
};
// Helper to find the k-th smallest element using Quickselect
const findKthSmallest = (arr: number[], k: number): number => {
let left = 0;
let right = arr.length - 1;
while (left < right) {
const pivotIndex = partition(arr, left, right);
if (pivotIndex === k) {
break;
} else if (pivotIndex < k) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return arr[k];
};
// Step 1: Find the median. Create a copy as findKthSmallest modifies the array.
const temp_nums = [...nums];
const median = findKthSmallest(temp_nums, Math.floor(n / 2));
// Step 2: 3-way partition on virtual indices
let left = 0, i = 0, right = n - 1;
while (i <= right) {
const mapped_i = mapIndex(i);
if (nums[mapped_i] > median) {
const mapped_left = mapIndex(left);
swap(mapped_left, mapped_i);
left++;
i++;
} else if (nums[mapped_i] < median) {
const mapped_right = mapIndex(right);
swap(mapped_right, mapped_i);
right--;
} else {
i++;
}
}
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.