Array Wave Arranger - Problem
Given an array of integers, rearrange the array elements to form a wave pattern where:
arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]...
The pattern alternates between greater-than-or-equal and less-than-or-equal comparisons. Your solution should work for both sorted and unsorted input arrays.
Note: Multiple valid wave arrangements may exist for the same input - return any valid arrangement.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1, 2, 3, 4]
›
Output:
[2,1,4,3]
💡 Note:
The wave pattern 2 ≥ 1 ≤ 4 ≥ 3 is achieved. At even indices we have peaks (2, 4) and at odd indices we have valleys (1, 3).
Example 2 — Already Sorted
$
Input:
arr = [10, 90, 49, 2, 1, 5, 23]
›
Output:
[90,10,49,1,5,2,23]
💡 Note:
After wave arrangement: 90 ≥ 10 ≤ 49 ≥ 1 ≤ 5 ≥ 2 ≤ 23. The pattern alternates correctly between peaks and valleys.
Example 3 — Two Elements
$
Input:
arr = [5, 1]
›
Output:
[5,1]
💡 Note:
With only two elements, 5 ≥ 1 already forms a valid wave pattern (peak followed by valley).
Constraints
- 2 ≤ arr.length ≤ 104
- -106 ≤ arr[i] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code