#324
Wiggle Sort II
MediumArrayDivide and ConquerGreedySortingQuickselectSortingTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(n!) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution involves sorting the array and then cleverly rearranging it using a two-pointer technique. This ensures that we can achieve the desired wiggle sort in linear time while maintaining the required conditions.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array.
- 2Step 2: Create a new array of the same length to hold the wiggle sorted result.
- 3Step 3: Use two pointers to fill the new array: one for the larger half and one for the smaller half.
- 4Step 4: Place elements in the new array according to the wiggle pattern.
solution.py17 lines
1# Full working Python code
2def wiggleSort(nums):
3 nums.sort()
4 n = len(nums)
5 result = [0] * n
6 left, right = (n + 1) // 2 - 1, n - 1
7 for i in range(n):
8 if i % 2 == 0:
9 result[i] = nums[left]
10 left -= 1
11 else:
12 result[i] = nums[right]
13 right -= 1
14 return result
15
16# Example usage
17print(wiggleSort([1, 5, 1, 1, 6, 4]))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for the result array.
- 1Sorting helps in easily accessing the smallest and largest elements.
- 2Using two pointers allows us to fill the result array in a structured manner.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.