Leetcode 280. Wiggle Sort

Problem Explanation

The problem requires us to rearrange an array in such a way that for every nums[i] at an even index, the next number at the odd index nums[i + 1] will be greater than or equal to nums[i] and for every nums[i] at an odd index, the next number at the even index nums[i + 1] will be less than or equal to nums[i].

For example, given an array [3,5,2,1,6,4], a possible solution could be [3,5,1,6,2,4].

Here are the steps of the algorithm:

  1. Traverse through the array starting from index 1
  2. Check two conditions for the each value in the array: a. If index is even, and the current element is greater than the previous element, b. If index is odd, and the current element is less than the previous element
  3. If the conditions hold, swap elements
  4. Continue to the next index, repeat steps 2-3 until the end of the array

Now let's walk through the algorithm with the sample example:

  1. Start at index i = 1, nums[1] = 5. Since i is odd and nums[i] >= nums[i - 1], the condition doesn't hold. So we move to the next index.
  2. At i = 2, nums[2] = 2. Since i is even and nums[i] <= nums[i - 1], the condition holds. So we swap nums[1] and nums[2] to get nums = [3,2,5,1,6,4].
  3. At i = 3, nums[3] = 1. Since i is odd and nums[i] >= nums[i - 1], the condition doesn't hold. So we swap nums[2] and nums[3] to get nums = [3,2,1,5,6,4].
  4. At i = 4, nums[4] = 6. Since i is even and nums[i] <= nums[i - 1], the condition holds. So we swap nums[3] and nums[4] to get nums = [3,2,1,6,5,4].
  5. At i = 5, nums[5] = 4. Since i is odd and nums[i] >= nums[i - 1], the condition doesn't hold. So we swap nums[4] and nums[5] to get nums = [3,2,1,6,4,5].

So after doing the above operations, the final array becomes nums = [3,5,1,6,2,4] which is the expected result.

Python Solution

1
2python
3class Solution:
4    def wiggleSort(self, nums):
5        for i in range(1, len(nums)):
6            if (i % 2 == 0 and nums[i] > nums[i - 1]) or (i % 2 == 1 and nums[i] < nums[i - 1]):
7                nums[i], nums[i - 1] = nums[i - 1], nums[i]

C++ Solution

1
2c++
3class Solution {
4public:
5    void wiggleSort(vector<int>& nums) {
6        for (int i = 1; i < nums.size(); ++i)
7            if ((i % 2 == 0 and nums[i] > nums[i - 1]) || (i % 2 == 1 and nums[i] < nums[i - 1]))
8                swap(nums[i], nums[i - 1]);
9    }
10};

Java Solution

1
2java
3class Solution {
4    public void wiggleSort(int[] nums) {
5        for (int i = 1; i < nums.length; ++i) {
6            if ((i % 2 == 0 && nums[i] > nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) {
7                int temp = nums[i];
8                nums[i] = nums[i - 1];
9                nums[i - 1] = temp;
10            }
11        }
12    }
13}

JavaScript Solution

1
2javascript
3class Solution {
4    wiggleSort(nums){
5        for (let i = 1; i < nums.length; ++i){
6            if ((i % 2 === 0 && nums[i] > nums[i - 1]) || (i % 2 === 1 && nums[i] < nums[i - 1])){
7                let temp = nums[i];
8                nums[i] = nums[i - 1];
9                nums[i - 1] = temp;
10            }
11        }
12    }
13}

C# Solution

1
2csharp
3public class Solution {
4    public void WiggleSort(int[] nums) {
5        for (int i = 1; i < nums.Length; ++i) {
6            if ((i % 2 == 0 && nums[i] > nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) {
7                int temp = nums[i];
8                nums[i] = nums[i - 1];
9                nums[i - 1] = temp;
10            }
11        }
12    }
13}

These solutions utilize a simple swap operation to traverse the array and reassign elements such that the required condition of nums[0] <= nums[1] >= nums[2] <= nums[3] etc. is fulfilled.This problem teaches us the important concept of iterating through an array by checking elements with respect to their preceding elements which is very useful in many array related problems. The key in understanding this problem lies in understanding the conditions of element comparison and swapping. Once this concept is grasped, implementing it using any programming language becomes straightforward.

In summary, we start at the second element and check for two conditions on each pass. If the current index is even, we need to make sure the preceding element is not larger, and swap elements if it is. If the current index is odd, we check if the preceding element is not smaller, and again swap elements if it is. We continue this process until we have traversed the entire array.

While solutions have been provided above in Python, C++, Java, JavaScript and C#, you can adopt and implement this algorithm in virtually any programming language that supports array data structure and conditional statements. The major takeaway here being understanding and implementing the logic of the algorithm, the syntax part then becomes quite straight ahead.

Given this scenario, it doesn’t matter what language the solution is coded in; understanding the logic and the algorithm is the key. This is essentially the concept of problem-solving using data structures and algorithms. With this solution, we use just a single pass to solve this problem traverse the array only once.. Thus, the time complexity of the provided solutions is O(n), where n is the length of the input array. It's hard to get more efficient than this which makes this approach quite satisfactory for large inputs.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫