DEV Community

JAYA SRI J
JAYA SRI J

Posted on

Move all negative element to end

The Code

class Solution:
    def segregateElements(self, arr):
        # Collect positives and negatives
        positives = [x for x in arr if x >= 0]
        negatives = [x for x in arr if x < 0]

        # Merge back into arr in-place
        arr[:] = positives + negatives
Enter fullscreen mode Exit fullscreen mode

Why This Approach?

This method is based on a simple idea:
Separate first, then combine
Instead of trying to rearrange elements inside the same array (which can get messy), we:
Extract positives
Extract negatives
Combine them in desired order
This reduces complexity in thinking and implementation.

Line-by-Line Explanation
Line 1: Collect Positive Elements
positives = [x for x in arr if x >= 0]

Why are we doing this?

We want all positive (and zero) elements together.
Using list comprehension makes it concise and readable.
It preserves the original order of elements
.
Time Complexity:
One full traversal → O(n)

Space Complexity:

Stores up to n elements → O(n)

Line 2: Collect Negative Elements
negatives = [x for x in arr if x < 0]
Why?

Separates negative values cleanly.
Maintains their original order (important for stability).
Time Complexity:
Another traversal → O(n)
Space Complexity:
Stores up to n elements → O(n)

Line 3: Merge Back Into Original Array

arr[:] = positives + negatives
Why?

Combines both lists so positives come first.
arr[:] ensures:

The original list is modified in-place
No new reference is created
Time Complexity:
Concatenation + assignment → O(n)

Space Complexity:

Temporary merged list → O(n)

Top comments (0)