DEV Community

Anjana R.K.
Anjana R.K.

Posted on

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 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 positives:
        arr[i] = num
        i += 1
    for num in negatives:
        arr[i] = num
        i += 1
Enter fullscreen mode Exit fullscreen mode

Time & Space Complexity

  • Time: O(n)
  • Space: O(n)

What I Learned

  • Maintaining order (stability) changes the approach
  • Sometimes extra space is needed for simpler logic
  • Always read constraints carefully before coding

Thanks for reading!
If you know a better in-place solution, feel free to share.

Top comments (0)