VOOZH about

URL: https://www.geeksforgeeks.org/dsa/move-negative-numbers-beginning-positive-end-constant-extra-space/

⇱ Move all negative numbers to beginning and positive to end with constant extra space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Move all negative numbers to beginning and positive to end with constant extra space

Last Updated : 11 Feb, 2025

Given an array containing both positive and negative numbers in random order. The task is to rearrange the array elements so that all negative numbers appear before all positive numbers.

Note:

  • Given array does not contain any zeroes.
  • Order of resultant array does not matter.

Example :

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5

[Naive approach] Using Sorting - O(nlogn) Time and O(1) Space

The idea is to sort the array of elements, this will make sure that all the negative elements will come before all the positive elements.

Below is the implementation of the above approach:


Output
-13 -12 -7 -6 -5 -3 5 6 11 

Time Complexity: O(n*log(n)), Where n is the length of the given array.
Auxiliary Space: O(1)

[Expected Approach - 1] Using Quick Sort Partition - O(n) time and O(1) space

The idea is to apply the partition process of quicksort. Initialize a variable (lets say j) to 0, and then traverse the array. If a negative number is encountered, then simply swap the current value and value at j, and increment the value of j.


Output
-12 -13 -5 -7 -3 -6 5 6 11 

Time complexity: O(n) 
Auxiliary Space: O(1)

[Expected Approach - 2] Using Two Pointer Method - O(n) time and O(1) space

The idea is to solve this problem with constant space and linear time is by using a two-pointer.

Step by step approach:

  1. Initialize two variables: left (set to 0) and right (set to n-1).
  2. While left is less than right, perform the following steps:
    1. While left is less than right, and value at left is negative, increment left.
    2. While right is greater than left, and value at right is positive, decrement right.
    3. After performing the above steps, if right is greater than left, it means value at left is positive and value at right is negative. So simply swap the two values.

Below is the implementation of the above approach:


Output
-12 -6 -13 -5 -3 -7 5 6 11 

Time Complexity: O(n)
Auxiliary Space: O(1)

[Expected Approach - 3] Using Two Pass - O(n) time and O(1) space

The idea is to traverse the array to find the number of negative numbers in the array. Then traverse the array again, and move the negative numbers to their respective indices.


Output
-12 -13 -5 -7 -3 -6 5 6 11 

Time Complexity: O(n)
Auxiliary Space: O(1)

Related Article:

Comment