Ctrl K

Strictly Low, High, Low

Medium
You get an integer array values. Rearrange its elements so that they strictly alternate low and high: values[0] < values[1] > values[2] < values[3] > values[4] < … The input is guaranteed to have such an arrangement. If there are several, any of them is accepted. Return the rearranged array. A sorting-based solution runs in O(n log n). Can you do it in O(n) time with O(1) extra space?
Example 1
values=[2, 2, 4, 1, 3, 3] → [2, 4, 2, 3, 1, 3]

For example [2, 4, 2, 3, 1, 3]: 2 < 4 > 2 < 3 > 1 < 3. Neighbours are never equal.

Example 2
values=[6, 5, 5, 4] → [5, 6, 4, 5]

The two 5s cannot sit next to each other. One valid answer is [5, 6, 4, 5]: 5 < 6 > 4 < 5.

Example 3
values=[9] → [9]
Constraints
  • 1 ≤ len(values) ≤ 5·10⁴
  • 0 ≤ values[i] ≤ 5000
  • A strict alternation of the input exists
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Highest Score MediumMost Common Values MediumNearest Points to the Base MediumK-th Largest Corner XOR MediumK-th Biggest Long Number Medium
loading Python…
Input
values=[2, 2, 4, 1, 3, 3]
Expected
[2, 4, 2, 3, 1, 3]

Run checks the first 3 tests in your browser. Submit checks all 35 tests on the server, hidden ones included.