MOVE ALL NEGATIVE ELEMENTS TO END

 

Segregating Positive and Negative Elements in an Array (Stable Order)

Introduction

In this problem, we are given an array containing both positive and negative integers. The goal is to rearrange the array such that all positive elements appear first, followed by negative elements without changing their original order.

This condition makes the problem slightly more challenging because we must maintain the relative order of elements.

Problem Statement

Given an array arr[], rearrange it so that:

  • All positive elements come first

  • All negative elements come at the end

  • The order of elements must be preserved

Example

Input:

arr = [1, -1, 3, 2, -7, -5, 11, 6]

Output:

[1, 3, 2, 11, 6, -1, -7, -5]

Solution Code

class Solution {
    public void segregateElements(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];
        int index = 0;

       
        for (int i = 0; i < n; i++) {
            if (arr[i] >= 0) {
                temp[index++] = arr[i];
            }
        }

        for (int i = 0; i < n; i++) {
            if (arr[i] < 0) {
                temp[index++] = arr[i];
            }
        }

       
        for (int i = 0; i < n; i++) {
            arr[i] = temp[i];
        }
    }
}

Approach Used: Using Auxiliary Array (Stable Partition)

Idea

We use a temporary array to:

  1. First store all positive elements in order

  2. Then store all negative elements in order

  3. Copy the result back to the original array

How It Works

  1. Create a new array temp[]

  2. Traverse original array:

    • Add all non-negative (≥ 0) elements

  3. Traverse again:

    • Add all negative elements

  4. Copy elements from temp back to arr

Why This Approach Was Chosen

  • Maintains the original order of elements (stable)

  • Simple and easy to understand

  • Avoids complex in-place shifting logic

Alternative Approaches

  • In-place partition (like quicksort)
     Does not maintain order

  • Two-pointer approach
     Difficult to maintain stability

Why not used?
Because the problem specifically requires maintaining the order, which is easier with an auxiliary array.

Time and Space Complexity

  • Time Complexity: O(n)

  • Space Complexity: O(n)

Important Observation

  • arr[i] >= 0 is used to include zero as a positive number

  • Order is preserved because elements are added sequentially

Conclusion

Using an auxiliary array is an effective way to segregate positive and negative elements while maintaining order. Although it uses extra space, it ensures correctness and simplicity, making it a preferred approach for this problem.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT