Introduction
The Rearrange Array by Positive and Negative Numbers problem involves arranging positive and negative elements alternately in the array.
Given an array arr[] containing both positive and negative integers, the task is to rearrange the array such that positive and negative numbers appear alternately while maintaining their relative order whenever possible.
This is an important array manipulation problem that helps in understanding Two Pointer Technique, array rearrangement, and in-place transformations.
Example
Input: arr[] = [1, -2, 3, -4, 5, -6]Output: [1, -2, 3, -4, 5, -6]
Explanation:
Positive and negative numbers already appear alternately.
Input: arr[] = [3, 1, -2, -5, 2, -4]
Output: [3, -2, 1, -5, 2, -4]
Explanation:
Positive and negative elements are rearranged alternately.
Relative order is maintained.
Constraints
1 <= n <= 10^5 -10^9 <= arr[i] <= 10^9
Approach 1 : Brute Force (Using Extra Arrays)
Explanation
The simplest way to solve this problem is:
- Store all positive numbers separately
- Store all negative numbers separately
- Place them alternately into the original array
This approach is easy to understand but requires extra space.
Steps
- Create:
- positive array
- negative array
- Traverse the original array.
- Store elements based on sign.
- Insert positive and negative elements alternately.
- Add remaining elements if any exist.
Dry Run
Input Array: [3, 1, -2, -5, 2, -4]Positive Elements:
[3, 1, 2]
Negative Elements:
[-2, -5, -4]
Place alternately:
3 → -2 → 1 → -5 → 2 → -4
Final Result:
[3, -2, 1, -5, 2, -4]
Brute Force Code
Complexity Analysis
Time Complexity: O(n)
Explanation:
The array is traversed once.
Space Complexity: O(n)
Explanation:Extra arrays are used to store positive and negative elements.
Approach 2 : Optimized Solution (Two Pointer Placement)
Explanation
Instead of storing elements separately and then merging, we can directly place elements into correct positions.
The idea is:
- Positive numbers go to even indices
- Negative numbers go to odd indices
This maintains alternating order efficiently.
Steps
- Create result array of size n.
- Initialize:
- positiveIndex = 0
- negativeIndex = 1
- Traverse the array.
- Place:
- positive elements at even positions
- negative elements at odd positions
- Return rearranged array.
Dry Run
Input Array: [3, 1, -2, -5, 2, -4]Initially:
positiveIndex = 0
negativeIndex = 1
Traverse 3:
Positive element
Place at index 0
Traverse 1:
Positive element
Place at index 2
Traverse -2:
Negative element
Place at index 1
Traverse -5:
Negative element
Place at index 3
Traverse 2:
Place at index 4
Traverse -4:
Place at index 5
Final Result:
[3, -2, 1, -5, 2, -4]
Optimized Code