Problem · Array
Alternate Positive and Negative Values
Learn this problemProblem statement
Given an integer array nums containing only non-zero values, return a rearrangement whose signs alternate at every adjacent position.
The counts of positive and negative values differ by at most one. The more frequent sign must appear first; when the counts are equal, a positive value must appear first. Preserve the relative order of the positive values and preserve the relative order of the negative values.
Function
alternateSigns(nums: int[]) → int[]Examples
Example 1
nums = [3,-2,1,-5]return = [3,-2,1,-5]The counts are equal, so positive starts. Both sign groups already appear in their stable alternating order.
Example 2
nums = [-4,1,2,-5]return = [1,-4,2,-5]Positive starts because the counts are equal. Positives remain [1,2] and negatives remain [-4,-5].
Example 3
nums = [-1,4,-2,5,-3]return = [-1,4,-2,5,-3]Negative values are more frequent, so a negative starts and ends the stable alternation.
Constraints
1 <= nums.length <= 200000.-10^9 <= nums[i] <= 10^9.nums[i] != 0.- The positive and negative counts differ by at most one.