Loading content...
Given an array of integers nums, rearrange the elements in-place so that they form an alternating high-low wave pattern. Specifically, the reordered array must satisfy the following strict inequalities at every adjacent position:
nums[0] < nums[1] > nums[2] < nums[3] > nums[4] < nums[5] ...
In other words:
This creates a distinctive wave-like pattern where values alternately rise and fall, resembling peaks and valleys when visualized graphically.
Key Requirements:
Visualization:
Original: [1, 5, 1, 1, 6, 4]
Valid Wave Pattern:
6 5
/ \ / \
1 1 1 4
peaks at odd indices (1, 3, 5)
valleys at even indices (0, 2, 4)
This problem challenges you to think about element placement strategies, median-finding algorithms, and space-efficient transformations.
nums = [1, 5, 1, 1, 6, 4][1, 6, 1, 5, 1, 4]After rearrangement: 1 < 6 > 1 < 5 > 1 < 4. The element at index 1 (value 6) is greater than its neighbors at indices 0 and 2 (values 1 and 1). Similarly, the element at index 3 (value 5) is greater than its neighbors. Another valid arrangement is [1, 4, 1, 5, 1, 6].
nums = [1, 3, 2, 2, 3, 1][2, 3, 1, 3, 1, 2]After rearrangement: 2 < 3 > 1 < 3 > 1 < 2. Each element at an odd index is strictly greater than its adjacent elements. This demonstrates handling duplicate values in the input array.
nums = [1, 2, 3, 4, 5][3, 5, 2, 4, 1]After rearrangement: 3 < 5 > 2 < 4 > 1. This shows how a sorted ascending sequence can be transformed into a wave pattern. The median value 3 plays a key role in enabling valid placement.
Constraints