This approach involves creating two separate lists to store positive and negative numbers. After separating, we iterate through both lists simultaneously, placing elements alternatively from each into a new result list. This ensures that conditions for alternating signs and preserving order are met.
Time Complexity: O(n); Space Complexity: O(n).
1function rearrangeArray(nums) {
2 const pos = [];
3 const neg = [];
4 for (let num of nums) {
5 if (num > 0) pos.push(num);
6 else neg.push(num);
7 }
8
9 const result = [];
10 for (let i = 0; i < pos.length; i++) {
11 result.push(pos[i]);
12 result.push(neg[i]);
13 }
14 return result;
15}
16
17const nums = [3, 1, -2, -5, 2, -4];
18console.log(rearrangeArray(nums));
This JavaScript solution uses arrays to collect positive and negative numbers then combines them alternately into a result array.
This approach attempts to rearrange the array in-place with the help of two pointers: one for the next positive element and one for the next negative. Starting with the assumption that the first element should be positive, iterate over the array and swap elements to their correct positions as needed.
Time Complexity: O(n); Space Complexity: O(1).
1function rearrangeArray(nums) {
2 let pos = 0, neg = 1;
3 while (pos < nums.length && neg < nums.length) {
4 if (nums[pos] > 0) {
5 pos += 2;
6 } else if (nums[neg] < 0) {
7 neg += 2;
8 } else {
9 [nums[pos], nums[neg]] = [nums[neg], nums[pos]]; // Swap
10 }
11 }
12 return nums;
13}
14
15const nums = [3, 1, -2, -5, 2, -4];
16console.log(rearrangeArray(nums));
This JavaScript code performs direct swaps in the input array to achieve the rearrangement with alternating order.