Rearrange Array Elements by Sign
MediumArraySorting
Description
Rearrange array of equal positive and negative numbers so they alternate, starting with positive, maintaining relative order within signs. Return the result as an array.
Examples
Input:
nums = [3,1,-2,-5,2,-4]Output:
[3,-2,1,-5,2,-4]Explanation:
Positives [3,1,2] and negatives [-2,-5,-4]. Interleave: [3,-2,1,-5,2,-4], starting with positive.
Input:
nums = [-1,1]Output:
[1,-1]Explanation:
Rearranging to start with positive: place 1 first, then -1. Result is [1,-1].
Input:
nums = [7,-3,4,-8,9,-1,2,-6]Output:
[7,-3,4,-8,9,-1,2,-6]Explanation:
The array already alternates between positive and negative starting with positive, so no rearrangement is needed.
Constraints
- •
2 ≤ nums.length ≤ 2 × 10⁵