1. Sort and Direct Interleave (Brute Force)
Intuition
Sorting gives non-decreasing order. If we place smaller numbers at even indices and larger numbers at odd indices from highest to lowest, equal elements are spaced out.
When to apply: Use to understand the wiggle requirement nums[0] < nums[1] > nums[2]...
Sort & Interleave Trace
2 of 2 questions left todayInput: [1, 5, 1, 1, 6, 4]
Input: [1, 5, 1, 1, 6, 4]. Sort array: [1, 1, 1, 4, 5, 6].
import java.util.*; public class Main { public static class Solution { public void wiggleSort(int[] nums) { int[] copy = nums.clone(); Arrays.sort(copy); int n = nums.length; int left = (n - 1) / 2; int right = n - 1; for (int i = 0; i < n; i++) { if (i % 2 == 0) { nums[i] = copy[left--]; } else { nums[i] = copy[right--]; } } } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, 5, 1, 1, 6, 4}; sol.wiggleSort(nums); System.out.println("Wiggle Sorted: " + Arrays.toString(nums)); }}Time & Space Complexity
- Time complexity:
O(n log n)— Sorting takes O(n log n), copying to temporary array takes O(n). - Space complexity:
O(n)— O(n) auxiliary array to hold sorted elements.
Why Brute Force Doesn't Scale:
For N = 50,000, QuickSelect + Virtual Indexing runs in O(N) time with 0 extra memory allocation.
QuickSelect reduces the operations from ~800,000 to ~150,000 and eliminates 200KB of auxiliary heap allocations.