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).
1def rearrange_array(nums):
2 pos, neg = [], []
3 for num in nums:
4 if num > 0:
5 pos.append(num)
6 else:
7 neg.append(num)
8 result = []
9 for p, n in zip(pos, neg):
10 result.extend([p, n])
11 return result
12
13nums = [3, 1, -2, -5, 2, -4]
14print(rearrange_array(nums))
This Python solution uses two lists to separate positive and negative numbers, then interleaves them in the result list.
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 <stdio.h>
2
3void swap(int *a, int *b) {
4 int temp = *a;
5 *a = *b;
6 *b = temp;
7}
8
9void rearrange(int* nums, int numsSize) {
10 int pos = 0, neg = 1;
11 while (pos < numsSize && neg < numsSize) {
12 if (nums[pos] > 0) pos += 2;
13 else if (nums[neg] < 0) neg += 2;
14 else swap(&nums[pos], &nums[neg]);
15 }
16}
17
18int main() {
19 int nums[] = {3, 1, -2, -5, 2, -4};
20 int numsSize = 6;
21 rearrange(nums, numsSize);
22 for (int i = 0; i < numsSize; i++) printf("%d ", nums[i]);
23 return 0;
24}
In this in-place C solution, pointers keep track of the correct next position for positive and negative elements, swapping where necessary.