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
INPUTALGORITHMRESULTOriginal Array12340123Need: arr[0] >= arr[1] <= arr[2] >= arr[3]1Check i=1: valley position22 > 1, violates valley rule3Swap arr[0] and arr[1]4Continue for remaining positionsWave Pattern2143peakvalleypeakvalley2 >= 1 <= 4 >= 3Valid Wave Pattern!Key Insight:Single pass with local swaps creates wave pattern without full sorting - O(n) time, O(1) spaceTutorialsPoint - Array Wave Arranger | Single Pass Wave Formation
Asked in
Amazon 35 Microsoft 28 Google 22 Adobe 18
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen