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).
1#include <stdio.h>
2
3void rearrange(int* nums, int numsSize, int* result) {
4 int posIndex = 0, negIndex = 0;
5 int pos[numsSize/2], neg[numsSize/2];
6
7 for (int i = 0; i < numsSize; i++) {
8 if (nums[i] > 0) pos[posIndex++] = nums[i];
9 else neg[negIndex++] = nums[i];
10 }
11
12 posIndex = negIndex = 0;
13 for (int i = 0; i < numsSize; i += 2) {
14 result[i] = pos[posIndex++];
15 result[i + 1] = neg[negIndex++];
16 }
17}
18
19int main() {
20 int nums[] = {3, 1, -2, -5, 2, -4};
21 int result[6];
22 rearrange(nums, 6, result);
23 for(int i = 0; i < 6; i++) printf("%d ", result[i]);
24 return 0;
25}
This C program separates the positive and negative numbers into two arrays, then fills the result array in alternating order.
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).
1#include <iostream>
2#include <vector>
3using namespace std;
4
5void rearrangeArray(vector<int>& nums) {
6 int pos = 0, neg = 1;
7 while (pos < nums.size() && neg < nums.size()) {
8 if (nums[pos] > 0) pos += 2;
9 else if (nums[neg] < 0) neg += 2;
10 else swap(nums[pos], nums[neg]);
11 }
12}
13
14int main() {
15 vector<int> nums = {3, 1, -2, -5, 2, -4};
16 rearrangeArray(nums);
17 for (int num : nums) cout << num << " ";
18 return 0;
19}
This C++ solution uses in-place swaps to ensure alternating positive and negative integers, handled via two pointers.