Alternating rearrangement of positive and negative numbers preserving order.
Problem Statement
Examples
Input: nums = [3, 1, -2, -5, 2, -4]
Output: [3, -2, 1, -5, 2, -4]
Explanation: Combining the input according to Rearrange array elements by sign logic yields [3, -2, 1, -5, 2, -4].
Input: nums = [-1, 1]
Output: [1, -1]
Explanation: Combining the input according to Rearrange array elements by sign logic yields [1, -1].
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
Since positive elements belong at even positions (0, 2, 4, ...) and negative elements at odd positions (1, 3, 5, ...), we can place each element directly into an output array of size N in one pass using two index pointers.
Step-by-Step Approach
- Allocate
result = new Array(nums.length). - Initialize
posIndex = 0andnegIndex = 1. - Iterate through
numinnums: - If
num > 0, setresult[posIndex] = num, thenposIndex += 2. - If
num < 0, setresult[negIndex] = num, thennegIndex += 2. - Return
result.
Optimal Implementation (JavaScript)
function rearrangeArray(nums) {
const result = new Array(nums.length);
let posIndex = 0, negIndex = 1;
for (let num of nums) {
if (num > 0) {
result[posIndex] = num;
posIndex += 2;
} else {
result[negIndex] = num;
negIndex += 2;
}
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Array of size 2: [pos, neg] or [neg, pos].
- Large alternating numbers.