DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Move Negative Elements to End While Maintaining Order

Problem Statement:
Given an unsorted array containing both positive and negative integers, rearrange the array such that all negative elements are moved to the end without changing the order of positive and negative elements.

Example:
Input: [1, -1, 3, 2, -7, -5, 11, 6]
Output: [1, 3, 2, 11, 6, -1, -7, -5]

Approach:
We use two separate lists:

  • One for positive elements
  • One for negative elements

Then we combine both lists and update the original array.

Code:

def rearrange(arr):
positives = []
negatives = []

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

arr[:] = positives + negatives
Enter fullscreen mode Exit fullscreen mode

Explanation:
This method preserves the order of elements. All positive numbers are stored first, followed by all negative numbers.

Time Complexity:
O(n), since we traverse the array once

Space Complexity:
O(n), since extra space is used

Top comments (0)