Rearrange Array Elements by Sign - Problem
You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should return the array of nums such that the array follows the given conditions:
- Every consecutive pair of integers have opposite signs.
- For all integers with the same sign, the order in which they were present in
numsis preserved. - The rearranged array begins with a positive integer.
Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,1,-2,-5,2,-4]
›
Output:
[3,-2,1,-5,2,-4]
💡 Note:
Positive numbers [3,1,2] are placed at even indices (0,2,4), negative numbers [-2,-5,-4] at odd indices (1,3,5), preserving original order within each sign.
Example 2 — Simple Case
$
Input:
nums = [-1,1]
›
Output:
[1,-1]
💡 Note:
Only one positive (1) and one negative (-1). Result starts with positive at index 0, negative at index 1.
Example 3 — Multiple Elements
$
Input:
nums = [1,2,-3,-4,5,-6]
›
Output:
[1,-3,2,-4,5,-6]
💡 Note:
Positives [1,2,5] maintain order at indices 0,2,4. Negatives [-3,-4,-6] maintain order at indices 1,3,5.
Constraints
- 2 ≤ nums.length ≤ 2 × 105
- nums.length is even
- 1 ≤ |nums[i]| ≤ 106
- nums consists of equal number of positive and negative integers
Visualization
Tap to expand
Understanding the Visualization
1
Input
Mixed array: [3,1,-2,-5,2,-4]
2
Process
Place positives at even indices, negatives at odd indices
3
Output
Alternating pattern: [3,-2,1,-5,2,-4]
Key Takeaway
🎯 Key Insight: Use two pointers to directly place elements at their target positions in one pass
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code