🔄 Move All Negative Elements to End – Python
Hi All,
Today I solved an interesting array problem: Move all negative elements to the end of the array while maintaining order.
📌 Problem Statement
Given an array containing both positive and negative integers, move all negative elements to the end.
⚠️ Conditions:
- Maintain the order of elements
- Perform operation in-place
- Do not return a new array
🔍 Examples
Example 1:
arr = [1, -1, 3, 2, -7, -5, 11, 6]
Output:
[1, 3, 2, 11, 6, -1, -7, -5]
Example 2:
arr = [-5, 7, -3, -4, 9, 10, -1, 11]
Output:
[7, 9, 10, 11, -5, -3, -4, -1]
💡 Approach
🔹 Method: Using Extra List (Stable Order)
👉 Since we must maintain order, we:
- Store all positive elements
- Store all negative elements
- Combine them back into original array
💻 Python Code
def move_negatives(arr):
positives = []
negatives = []
for num in arr:
if num >= 0:
positives.append(num)
else:
negatives.append(num)
# Modify original array (in-place)
arr[:] = positives + negatives
🔍 Dry Run
For:
arr = [1, -1, 3, -2]
Steps:
- positives → [1, 3]
- negatives → [-1, -2]
Final array:
[1, 3, -1, -2]
🖥️ Sample Output
Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]
Input: [-5, 7, -3, -4, 9, 10, -1, 11]
Output: [7, 9, 10, 11, -5, -3, -4, -1]
⚡ Complexity Analysis
- Time Complexity: O(n) ✅
- Space Complexity: O(n) ✅
🧠 Why not two-pointer swap?
👉 Normal swapping:
- Changes order ❌
- Not allowed in this problem
👉 This problem needs stable arrangement
✅ Conclusion
This problem helped me understand:
- Stable partitioning
- Maintaining order in arrays
- In-place modification using slicing
🚀 Useful concept for real-world data processing!
Top comments (0)