- Move all negative elements to end
Problem
Given an array, move all negative elements to the end while maintaining the order of positive elements.
Example:
Id="ex4"
Input: [1, -2, 3, -4, 5]
Output: [1, 3, 5, -2, -4]
Approach Used: Temporary Array (Stable Method)
Instead of modifying in-place, we:
1.Store all non-negative elements first
2.Then append all negative elements
Copy back to original array
Step-by-step explanation
Step 1: Create temp array
Python id="s1"
temp = []
Step 2: Add non-negative elements
Python id="s2"
for num in arr:
if num >= 0:
temp.append(num)
👉 Maintains original order
Step 3: Add negative elements
Python id="s3"
for num in arr:
if num < 0:
temp.append(num)
Step 4: Copy back
Python id="s4"
for i in range(len(arr)):
arr[i] = temp[i]
Full Code
`class Solution:
def segregateElements(self, arr):
temp = []
for num in arr:
if num >= 0:
temp.append(num)
for num in arr:
if num < 0:
temp.append(num)
for i in range(len(arr)):
arr[i] = temp[i]`
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n) ❗ (extra array used)
Conclusion
Your method is simple and stable
Best when order matters
In-place method is better when memory is limited
Top comments (0)