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).
1using System;
2using System.Collections.Generic;
3
4class RearrangeArray {
5 public static int[] Rearrange(int[] nums) {
6 List<int> pos = new List<int>();
7 List<int> neg = new List<int>();
8
9 foreach (int num in nums) {
10 if (num > 0) pos.Add(num);
11 else neg.Add(num);
12 }
13
14 int[] result = new int[nums.Length];
15 int posIndex = 0, negIndex = 0;
16 for (int i = 0; i < nums.Length; i += 2) {
17 result[i] = pos[posIndex++];
18 result[i + 1] = neg[negIndex++];
19 }
20 return result;
21 }
22
23 static void Main() {
24 int[] nums = {3, 1, -2, -5, 2, -4};
25 int[] result = Rearrange(nums);
26 Console.WriteLine(string.Join(" ", result));
27 }
28}
This C# solution separates positive and negative numbers into lists and constructs a new array by alternating elements from these lists.
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).
1def rearrange_array(nums):
2 pos, neg = 0, 1
3 while pos < len(nums) and neg < len(nums):
4 if nums[pos] > 0:
5 pos += 2
6 elif nums[neg] < 0:
7 neg += 2
8 else:
9 nums[pos], nums[neg] = nums[neg], nums[pos]
10 return nums
11
12nums = [3, 1, -2, -5, 2, -4]
13print(rearrange_array(nums))
By treating the input list as a single array, this Python approach rearranges elements in-place using two alternating pointers, ensuring no extra space is used.