Move All Negative Elements to End
Hi everyone! I solved an interesting array problem where we need to move all negative numbers to the end, but without disturbing the order of elements. Problem Given an array with positive and nega...

Source: DEV Community
Hi everyone! I solved an interesting array problem where we need to move all negative numbers to the end, but without disturbing the order of elements. Problem Given an array with positive and negative numbers, move all negative elements to the end while maintaining order. Example: Input: [1, -1, 3, 2, -7, -5, 11, 6] Output: [1, 3, 2, 11, 6, -1, -7, -5] My Approach At first, I thought of swapping elements, but that would disturb the order. Then I realized: We need a stable approach (order should not change) So I used two lists: One for positive numbers One for negative numbers Logic Traverse the array Store positives and negatives separately Put positives first, then negatives back into array Code (Python) class Solution: def segregateElements(self, arr): positives = [] negatives = [] # Separate positives and negatives while preserving order for num in arr: if num >= 0: positives.append(num) else: negatives.append(num) # Combine back into original array (in-place) i = 0 for num in p