Back to articles
Segregating Positive and Negative Elements

Segregating Positive and Negative Elements

via Dev.to PythonAshiq Omar

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

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles