Move Negative Elements to End While Maintaining Order

Published: (March 19, 2026 at 11:10 PM EDT)
1 min read
Source: Dev.to

Source: Dev.to

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 relative order of the positive and negative elements.

Example

Input:

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

Output:

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

Approach

  1. Iterate through the array once.
  2. Collect positive (or zero) numbers in one list.
  3. Collect negative numbers in another list.
  4. Concatenate the two lists and overwrite 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

Explanation

  • The method preserves the original order because elements are appended to the positives and negatives lists in the order they appear.
  • After processing, the positives list is placed first, followed by the negatives list, achieving the required arrangement.

Time Complexity

  • O(n) – the array is traversed only once.

Space Complexity

  • O(n) – additional space is used for the two auxiliary lists.
0 views
Back to Blog

Related posts

Read more »

Finding Minimum and Maximum in an Array

Problem Statement Given an array of numbers, we need to find the smallest minimum and largest maximum elements. Example Input: 1, 4, 3, 5, 8, 6 Output: 1, 8 Ap...

To Find the max & min elements in a array

Approach To find the minimum and maximum elements in an array without using built‑in min or max functions, initialize both min and max with the first element o...

ASSIGNMENT 20

Problem Statement You are given a sorted array that has been rotated at an unknown index. Your task is to find the index of a target element. Constraints - Eve...