DEV Community

Mubashir
Mubashir

Posted on

Move All Negative Elements End

OVERVIEW
In this task, I worked on rearranging an array that contains both positive and negative integers. The goal was to move all negative elements to the end without changing the order of both positive and negative numbers.

MY APPROACH
I created a function that takes an array and rearranges it such that:

  1. All positive elements stay in the front
  2. All negative elements move to the end
  3. The order remains the same (stable).

EXAMPLE
INPUT : arr = [1, -2, 3, -4, 5, -6]
OUTPUT : [1, 3, 5, -2, -4, -6]

LOGIC IMPLEMENTED

  • Create two lists:
  • One for positive numbers
  • One for negative numbers
  • Loop through the array:
  • If element ≥ 0 → add to positive list
  • Else → add to negative list
  • Merge both lists
class Solution:
    def segregateElements(self, arr):
        pos = 0  # position for next positive element

        for i in range(len(arr)):
            if arr[i] >= 0:
                temp = arr[i]

                j = i
                while j > pos:
                    arr[j] = arr[j - 1]
                    j -= 1

                arr[pos] = temp
                pos += 1

        return arr 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)