LeetCode 324: Wiggle Sort II Solution

Master LeetCode problem 324 (Wiggle Sort II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we will first sort the array in non-decreasing order. Then, we will rearrange the sorted array in a "wiggle" pattern by placing the larger elements in the odd indices and the smaller elements in the even indices.

  1. Sort the array.
  2. Create two pointers, one starting from the end of the smaller half and the other starting from the end of the array.
  3. Alternate between placing elements from the larger half and the smaller half into the odd and even indices of the result array.

Time complexity: O(n log n) for sorting the array, where n is the number of elements in the array.
Space complexity: O(n) for the sorted array.

Solution Code

import java.util.Arrays;

class Solution {
    public void wiggleSort(int[] nums) {
        int[] sorted = nums.clone();
        Arrays.sort(sorted);
        
        int n = nums.length;
        int left = (n + 1) / 2 - 1;
        int right = n - 1;
        
        for (int i = 0; i < n; i++) {
            nums[i] = (i % 2 == 0) ? sorted[left--] : sorted[right--];
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 324 (Wiggle Sort II)?

This page provides optimized solutions for LeetCode problem 324 (Wiggle Sort II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 324 (Wiggle Sort II)?

The time complexity for LeetCode 324 (Wiggle Sort II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 324 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 324 in Java, C++, or Python.

Back to LeetCode Solutions