MOVE ALL NEGATIVE ELEMENTS TO END
Segregating Positive and Negative Elements in an Array (Stable Order)
Introduction
In this problem, we are given an array containing both positive and negative integers. The goal is to rearrange the array such that all positive elements appear first, followed by negative elements without changing their original order.
This condition makes the problem slightly more challenging because we must maintain the relative order of elements.
Problem Statement
Given an array arr[], rearrange it so that:
All positive elements come first
All negative elements come at the end
The order of elements must be preserved
Example
Input:
arr = [1, -1, 3, 2, -7, -5, 11, 6]
Output:
[1, 3, 2, 11, 6, -1, -7, -5]Solution Code
class Solution {
public void segregateElements(int[] arr) {
int n = arr.length;
int[] temp = new int[n];
int index = 0;
for (int i = 0; i < n; i++) {
if (arr[i] >= 0) {
temp[index++] = arr[i];
}
}
for (int i = 0; i < n; i++) {
if (arr[i] < 0) {
temp[index++] = arr[i];
}
}
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
}Approach Used: Using Auxiliary Array (Stable Partition)
Idea
We use a temporary array to:
First store all positive elements in order
Then store all negative elements in order
Copy the result back to the original array
How It Works
Create a new array
temp[]Traverse original array:
Add all non-negative (≥ 0) elements
Traverse again:
Add all negative elements
Copy elements from
tempback toarr
Why This Approach Was Chosen
Maintains the original order of elements (stable)
Simple and easy to understand
Avoids complex in-place shifting logic
Alternative Approaches
In-place partition (like quicksort)
Does not maintain orderTwo-pointer approach
Difficult to maintain stability
Why not used?
Because the problem specifically requires maintaining the order, which is easier with an auxiliary array.
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Important Observation
arr[i] >= 0is used to include zero as a positive numberOrder is preserved because elements are added sequentially
Conclusion
Using an auxiliary array is an effective way to segregate positive and negative elements while maintaining order. Although it uses extra space, it ensures correctness and simplicity, making it a preferred approach for this problem.
Comments
Post a Comment