Reorder an array so positive and negative values appear in alternating order while preserving their original relative order within each sign group.
Given an integer array nums containing the same number of positive and negative integers, rearrange the elements so that:
- positive and negative numbers appear in alternating order, and
- the first element is positive.
Keep the relative order of the positive numbers the same as in the original array, and do the same for the negative numbers.
Return the rearranged array.
Input Format
- An integer array
nums. numscontains an equal number of positive and negative integers.- Every element is non-zero.
Output Format
- Return an array of the same length as
nums. - The returned array must alternate positive and negative values, starting with a positive value.
Constraints
nums.lengthis evennums[i] != 0- The number of positive integers equals the number of negative integers
- Preserve relative order among positive numbers and among negative numbers
Example 1
Input
nums = [3,1,-2,-5,2,-4]
Output
[3,-2,1,-5,2,-4]
Explanation
Positive numbers keep their order: [3,1,2]. Negative numbers keep their order: [-2,-5,-4]. Placing them alternately starting with a positive number gives [3,-2,1,-5,2,-4].
Example 2
Input
nums = [-1,1]
Output
[1,-1]
Explanation
The array must start with a positive number, so the only valid rearrangement is [1,-1].
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.