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:

C++
// C++ program to Move all negative numbers
// to beginning and positive to end
#include <bits/stdc++.h>
using namespace std;

vector<int> move(vector<int> &arr) {
    sort(arr.begin(), arr.end());
    return arr;
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    vector<int> ans = move(arr);
    
    for (auto num: ans) {
        cout << num << " ";
    }
    cout<<endl;

    return 0;
}
Java
// Java program to Move all negative numbers
// to beginning and positive to end

import java.util.Arrays;

class GfG {

    static int[] move(int[] arr) {
        Arrays.sort(arr);
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);
        
        for (int num : ans) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
# Python program to Move all negative numbers
# to beginning and positive to end

def move(arr):
    arr.sort()
    return arr

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    ans = move(arr)
    
    for num in ans:
        print(num, end=" ")
    print()
C#
// C# program to Move all negative numbers
// to beginning and positive to end

using System;

class GfG {

    static int[] move(int[] arr) {
        Array.Sort(arr);
        return arr;
    }

    static void Main(string[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);
        
        foreach (int num in ans) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Move all negative numbers
// to beginning and positive to end

function move(arr) {
    arr.sort((a, b) => a - b);
    return arr;
}

const arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
const ans = move(arr);

for (const num of ans) {
	console.log(num);
}

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.

C++
// C++ program to Move all negative numbers
// to beginning and positive to end
#include <bits/stdc++.h>
using namespace std;

vector<int> move(vector<int> &arr) {
    int j = 0;
    for (int i=0; i<arr.size(); i++) {
        
        // If negative number is present
        // swap it with arr[j]
        if (arr[i]<0) {
            swap(arr[i], arr[j]);
            j++;
        }
    }
    
    return arr;
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    vector<int> ans = move(arr);
    
    for (auto num: ans) {
        cout << num << " ";
    }
    cout<<endl;

    return 0;
}
Java
// Java program to Move all negative numbers
// to beginning and positive to end

class GfG {

    static int[] move(int[] arr) {
        int j = 0;
        for (int i = 0; i < arr.length; i++) {

            // If negative number is present
            // swap it with arr[j]
            if (arr[i] < 0) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                j++;
            }
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        for (int num : ans) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
# Python program to Move all negative numbers
# to beginning and positive to end

def move(arr):
    j = 0
    for i in range(len(arr)):
        
        # If negative number is present
        # swap it with arr[j]
        if arr[i] < 0:
            arr[i], arr[j] = arr[j], arr[i]
            j += 1
    
    return arr

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    ans = move(arr)
    
    for num in ans:
        print(num, end=" ")
    print()
C#
// C# program to Move all negative numbers
// to beginning and positive to end

using System;

class GfG {

    static int[] move(int[] arr) {
        int j = 0;
        for (int i = 0; i < arr.Length; i++) {

            // If negative number is present
            // swap it with arr[j]
            if (arr[i] < 0) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                j++;
            }
        }

        return arr;
    }

    static void Main(string[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        foreach (int num in ans) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Move all negative numbers
// to beginning and positive to end

function move(arr) {
    let j = 0;
    for (let i = 0; i < arr.length; i++) {

        // If negative number is present
        // swap it with arr[j]
        if (arr[i] < 0) {
            [arr[i], arr[j]] = [arr[j], arr[i]];
            j++;
        }
    }

    return arr;
}

const arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
const ans = move(arr);

for (const num of ans) {
    process.stdout.write(num + " ");
}
console.log();

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:

C++
// C++ program to Move all negative numbers
// to beginning and positive to end
#include <bits/stdc++.h>
using namespace std;

vector<int> move(vector<int> &arr) {
    int left = 0, right = arr.size()-1;
    while (left<right) {
        
        // increment left while arr[left]
        // is negative
        while (left<right && arr[left]<0) {
            left++;
        }
        
        // decrement right while arr[right]
        // is positive
        while (right>left && arr[right]>0) {
            right--;
        }
        
        // swap the two values.
        if (right>left) {
            swap(arr[left], arr[right]);
            left++;
            right--;
        }
    }
    
    return arr;
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    vector<int> ans = move(arr);
    
    for (auto num: ans) {
        cout << num << " ";
    }
    cout<<endl;

    return 0;
}
Java
// Java program to Move all negative numbers
// to beginning and positive to end

class GfG {

    static int[] move(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {

            // increment left while arr[left]
            // is negative
            while (left < right && arr[left] < 0) {
                left++;
            }

            // decrement right while arr[right]
            // is positive
            while (right > left && arr[right] > 0) {
                right--;
            }

            // swap the two values.
            if (right > left) {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        for (int num : ans) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
# Python program to Move all negative numbers
# to beginning and positive to end

def move(arr):
    left, right = 0, len(arr) - 1
    while left < right:

        # increment left while arr[left]
        # is negative
        while left < right and arr[left] < 0:
            left += 1

        # decrement right while arr[right]
        # is positive
        while right > left and arr[right] > 0:
            right -= 1

        # swap the two values.
        if right > left:
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1

    return arr

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    ans = move(arr)

    for num in ans:
        print(num, end=" ")
    print()
C#
// C# program to Move all negative numbers
// to beginning and positive to end

using System;

class GfG {

    static int[] move(int[] arr) {
        int left = 0, right = arr.Length - 1;
        while (left < right) {

            // increment left while arr[left]
            // is negative
            while (left < right && arr[left] < 0) {
                left++;
            }

            // decrement right while arr[right]
            // is positive
            while (right > left && arr[right] > 0) {
                right--;
            }

            // swap the two values.
            if (right > left) {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
        }

        return arr;
    }

    static void Main(string[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        foreach (int num in ans) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Move all negative numbers
// to beginning and positive to end

function move(arr) {
    let left = 0, right = arr.length - 1;
    while (left < right) {

        // increment left while arr[left]
        // is negative
        while (left < right && arr[left] < 0) {
            left++;
        }

        // decrement right while arr[right]
        // is positive
        while (right > left && arr[right] > 0) {
            right--;
        }

        // swap the two values.
        if (right > left) {
            [arr[left], arr[right]] = [arr[right], arr[left]];
            left++;
            right--;
        }
    }

    return arr;
}

const arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
const ans = move(arr);

for (const num of ans) {
    process.stdout.write(num + " ");
}
console.log();

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.

C++
// C++ program to Move all negative numbers
// to beginning and positive to end
#include <bits/stdc++.h>
using namespace std;

vector<int> move(vector<int> &arr) {
    int cnt = 0;
    
    for (auto num: arr) {
        if (num<0) cnt++;
    }
    
    int i = 0;
    for (int j=0; j<cnt; j++) {
        while (i<arr.size() && arr[i]>=0) i++;
        
        // Swap the values
        swap(arr[j], arr[i]);
        i++;
    }
    
    return arr;
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    vector<int> ans = move(arr);
    
    for (auto num: ans) {
        cout << num << " ";
    }
    cout<<endl;

    return 0;
}
Java
// Java program to Move all negative numbers
// to beginning and positive to end

class GfG {

    static int[] move(int[] arr) {
        int cnt = 0;

        for (int num : arr) {
            if (num < 0) cnt++;
        }

        int i = 0;
        for (int j = 0; j < cnt; j++) {
            while (i < arr.length && arr[i] >= 0) i++;

            // Swap the values
            int temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
            i++;
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        for (int num : ans) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}
Python
# Python program to Move all negative numbers
# to beginning and positive to end

def move(arr):
    cnt = 0

    for num in arr:
        if num < 0:
            cnt += 1

    i = 0
    for j in range(cnt):
        while i < len(arr) and arr[i] >= 0:
            i += 1

        # Swap the values
        arr[j], arr[i] = arr[i], arr[j]
        i += 1

    return arr

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    ans = move(arr)

    for num in ans:
        print(num, end=" ")
    print()
C#
// C# program to Move all negative numbers
// to beginning and positive to end

using System;

class GfG {

    static int[] move(int[] arr) {
        int cnt = 0;

        foreach (int num in arr) {
            if (num < 0) cnt++;
        }

        int i = 0;
        for (int j = 0; j < cnt; j++) {
            while (i < arr.Length && arr[i] >= 0) i++;

            // Swap the values
            int temp = arr[j];
            arr[j] = arr[i];
            arr[i] = temp;
            i++;
        }

        return arr;
    }

    static void Main(string[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        int[] ans = move(arr);

        foreach (int num in ans) {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// JavaScript program to Move all negative numbers
// to beginning and positive to end

function move(arr) {
    let cnt = 0;

    for (const num of arr) {
        if (num < 0) cnt++;
    }

    let i = 0;
    for (let j = 0; j < cnt; j++) {
        while (i < arr.length && arr[i] >= 0) {
            i++;
        }

        // Swap the values
        [arr[j], arr[i]] = [arr[i], arr[j]];
        i++;
    }

    return arr;
}

const arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
const ans = move(arr);

for (const num of ans) {
    process.stdout.write(num + " ");
}
console.log();

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

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

Related Article:

Comment