Rearranging elements in an array while preserving order is a common and important problem in programming.
This problem focuses on separating positive and negative numbers efficiently.
๐ Problem Statement
Given an array arr[] containing both positive and negative integers:
๐ Move all negative elements to the end
๐ Maintain the relative order of both positive and negative elements
๐ Perform the operation in-place
๐ Examples
Example 1:
Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Example 2:
Input: [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
๐ง Concept
We need to:
- Keep positive elements in original order
- Move negative elements to the end in same order
๐ This is similar to a stable partition problem
๐ Approach: Using Extra Space (Stable & Simple)
Step-by-Step:
- Create two lists:
- One for positive elements
-
One for negative elements
- Traverse the array:
Add positives to one list
-
Add negatives to another
- Merge them back into the original array
๐ป Python Code
```python id="q7c9vx"
def move_negatives(arr):
positives = []
negatives = []
for num in arr:
if num >= 0:
positives.append(num)
else:
negatives.append(num)
# Combine and modify original array
arr[:] = positives + negatives
return arr
Example
print(move_negatives([1, -1, 3, 2, -7, -5, 11, 6]))
---
## ๐งพ Dry Run
For:
```id="6cdm8c"
arr = [1, -1, 3, 2, -7, -5, 11, 6]
- Positives โ
[1, 3, 2, 11, 6] - Negatives โ
[-1, -7, -5]
๐ Final โ [1, 3, 2, 11, 6, -1, -7, -5]
โก Time and Space Complexity
-
Time Complexity:
O(n) -
Space Complexity:
O(n)
๐ Alternative Approach (In-Place but Complex)
We can also solve this without extra space using a two-pointer approach, but:
โ It may not maintain order easily
โ Requires shifting elements (costly operations)
๐ Hence, the extra-space approach is preferred when order must be preserved
๐งฉ Where Is This Used?
- Data filtering
- Stable partition problems
- Interview questions
- Stream processing
๐ Conclusion
To move all negative elements to the end while maintaining order, the best approach is:
โ Use extra space
โ Keep logic simple and readable
โ Maintain stability
Top comments (0)