280. Wiggle Sort
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 in-place to follow a specific "wiggle" pattern: nums[0] = nums[2] <= nums[3].... This means every element at an even index must be less than or equal to its right neighbor, and every element at an odd index must be greater than or equal to its right neighbor.
Solution
Wiggle Sort in Python
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
# Iterate through the array up to the second to last element.
for i in range(n - 1):
# If i is even, we need nums[i] <= nums[i+1].
# If i is odd, we need nums[i] >= nums[i+1].
# This can be combined into one check.
if (i % 2 == 0 and nums[i] > nums[i+1]) or \
(i % 2 != 0 and nums[i] < nums[i+1]):
# Swap elements if the condition is violated.
nums[i], nums[i+1] = nums[i+1], nums[i]
Wiggle Sort in Java
class Solution {
public void wiggleSort(int[] nums) {
int n = nums.length;
// Iterate through the array up to the second to last element.
for (int i = 0; i < n - 1; i++) {
// A single condition can check both even and odd cases.
// For even i: (i % 2 == 0) is true. The condition becomes nums[i] > nums[i+1].
// For odd i: (i % 2 == 0) is false. The condition becomes nums[i] < nums[i+1].
if ((i % 2 == 0) == (nums[i] > nums[i+1])) {
// Swap elements if the condition is violated.
int temp = nums[i];
nums[i] = nums[i+1];
nums[i+1] = temp;
}
}
}
}
Wiggle Sort in C++
class Solution {
public:
void wiggleSort(vector<int>& nums) {
int n = nums.size();
// Iterate through the array up to the second to last element.
for (int i = 0; i < n - 1; ++i) {
// If i is even, nums[i] should be <= nums[i+1].
if (i % 2 == 0) {
if (nums[i] > nums[i+1]) {
swap(nums[i], nums[i+1]);
}
}
// If i is odd, nums[i] should be >= nums[i+1].
else {
if (nums[i] < nums[i+1]) {
swap(nums[i], nums[i+1]);
}
}
}
}
};
Wiggle Sort in TypeScript
/**
Do not return anything, modify nums in-place instead.
*/
function wiggleSort(nums: number[]): void {
const n = nums.length;
// Iterate through the array up to the second to last element.
for (let i = 0; i < n - 1; i++) {
// If i is even, nums[i] should be <= nums[i+1].
if (i % 2 === 0) {
if (nums[i] > nums[i+1]) {
// Swap elements if the condition is violated.
[nums[i], nums[i+1]] = [nums[i+1], nums[i]];
}
}
// If i is odd, nums[i] should be >= nums[i+1].
else {
if (nums[i] < nums[i+1]) {
// Swap elements if the condition is violated.
[nums[i], nums[i+1]] = [nums[i+1], nums[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.