DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Segregating Positive and Negative Elements

In this task, I worked on rearranging an array such that all non-negative (positive + zero) elements come first, followed by all negative elements.
This problem helps in understanding array traversal and rearrangement techniques.
What I Did:
I created a function segregateElements that takes an array as input and rearranges it so that:
All positive (and zero) values appear first
All negative values appear at the end
Example:
Input: [1, -2, 3, -4, 5, -6]

Output: [1, 3, 5, -2, -4, -6]
How I Solved It:
Instead of swapping elements in-place (which can get messy), I used a simple and clean approach with two lists.
Step-by-step approach:

I created two separate lists:

  • positives → to store non-negative elements
  • negatives → to store negative elements Then I traversed the array:
  • If the number is ≥ 0 → add to positives
  • Otherwise → add to negatives
  • Finally, I combined both lists and updated the original array
    Code:'''python
    class Solution:
    def segregateElements(self, arr):
    positives = []
    negatives = []

    for num in arr:
        if num >= 0:
            positives.append(num)
        else:
            negatives.append(num)
    
    arr[:] = positives + negatives '''
    

    How It Works
    The algorithm separates elements into two groups
    Maintains the original order of elements (stable approach)
    Combines both lists to form the final result
    Using arr[:] = ... ensures the original array is modified instead of creating a new one.

Top comments (0)