The Wayback Machine - https://web.archive.org/web/20240818163948/https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/
Open In App

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

Last Updated : 29 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.

Examples : 

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

Note: Order of elements is not important here.

Naive approach: 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++
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void move(vector<int>& arr){
  sort(arr.begin(),arr.end());
}
int main() {

    vector<int> arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
      move(arr);
    for (int e : arr)
       cout<<e << " ";
    return 0;
}

// This code is contributed by repakaeshwaripriya
Java
// Java program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space
import java.util.*;
public class Gfg {
   
    public static void move(int[] arr)
    {
        Arrays.sort(arr);
    }

    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        move(arr);
        for (int e : arr)
            System.out.print(e + " ");
    }
}
// This article is contributed by aadityapburujwale
Python3
# Python code for the same approach
def move(arr):
  arr.sort()

# driver code
arr = [ -1, 2, -3, 4, 5, 6, -7, 8, 9 ]
move(arr)
for e in arr:
    print(e , end = " ")

# This code is contributed by shinjanpatra
C#
// C# program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space
using System;
using System.Collections;
public class Gfg {
   
    public static void move(int[] arr)
    {
        Array.Sort(arr);
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        move(arr);
        foreach (int e in arr)
            Console.Write(e + " ");
    }
}
// This code is contributed by Saurabh Jaiswal
JavaScript
// JavaScript Code for the same approach

function move(arr){
    arr.sort();
}

// driver code
  
let arr = [ -1, 2, -3, 4, 5, 6, -7, 8, 9 ];
move(arr);
for (let e of arr)
    console.log(e , " ");
  
// This code is contributed by shinjanpatra

Output
-7 -3 -1 2 4 5 6 8 9 

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

Efficient Approach 1:
The idea is to simply apply the partition process of quicksort. 

C++
// A C++ program to put all negative
// numbers before positive numbers
#include <bits/stdc++.h>
using namespace std;

void rearrange(int arr[], int n)
{
    int j = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] < 0) {
            if (i != j)
                swap(arr[i], arr[j]);
            j++;
        }
    }
}

// A utility function to print an array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
}

// Driver code
int main()
{
    int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    rearrange(arr, n);
    printArray(arr, n);
    return 0;
}
Java
// Java program to put all negative
// numbers before positive numbers
import java.io.*;

class GFG {

    static void rearrange(int arr[], int n)
    {
        int j = 0, temp;
        for (int i = 0; i < n; i++) {
            if (arr[i] < 0) {
                if (i != j) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                j++;
            }
        }
    }

    // A utility function to print an array
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }

    // Driver code
    public static void main(String args[])
    {
        int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        int n = arr.length;

        rearrange(arr, n);
        printArray(arr, n);
    }
}

// This code is contributed by Nikita Tiwari.
Python3
# A Python 3 program to put
# all negative numbers before
# positive numbers

def rearrange(arr, n ) :

    # Please refer partition() in 
    # below post
    # https://www.geeksforgeeks.org / quick-sort / j = 0
    j = 0 
    for i in range(0, n) :
        if (arr[i] < 0) :
            temp = arr[i]
            arr[i] = arr[j]
            arr[j]= temp
            j = j + 1
    print(arr)

# Driver code
arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9]
n = len(arr)
rearrange(arr, n)


# This code is contributed by Nikita Tiwari.
C#
// C# program to put all negative
// numbers before positive numbers
using System;

class GFG {
    static void rearrange(int[] arr, int n)
    {

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

    // A utility function to print an array
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        int n = arr.Length;

        rearrange(arr, n);
        printArray(arr, n);
    }
}

// This code is contributed by nitin mittal.
JavaScript
// A JavaScript program to put all negative
// numbers before positive numbers

function rearrange(arr, n)
{
    let j = 0;
    for (let i = 0; i < n; i++) {
        if (arr[i] < 0) {
            if (i != j){
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
            j++;
        }
    }
}

// A utility function to print an array
function printArray(arr, n)
{
    for (let i = 0; i < n; i++)
        console.log(arr[i] + " ");
}

// Driver code
    let arr = [ -1, 2, -3, 4, 5, 6, -7, 8, 9 ];
    let n = arr.length;
    rearrange(arr, n);
    printArray(arr, n);


// This code is contributed by Surbhi Tyagi.
PHP
<?php 
// A PHP program to put all negative
// numbers before positive numbers

function rearrange(&$arr, $n)
{
    $j = 0;
    for ($i = 0; $i < $n; $i++)
    {
        if ($arr[$i] < 0) 
        {
            if ($i != $j)
            {
                $temp = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j] = $temp;
            }
            $j++;
        }
    }
}

// A utility function to print an array
function printArray(&$arr, $n)
{
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i]." ";
}

// Driver code
$arr = array(-1, 2, -3, 4, 5, 6, -7, 8, 9 );
$n = sizeof($arr);
rearrange($arr, $n);
printArray($arr, $n);

// This code is contributed by ChitraNayal
?>

Output
-1 -3 -7 4 5 6 2 8 9 

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

Two Pointer Approach: The idea is to solve this problem with constant space and linear time is by using a two-pointer or two-variable approach where we simply take two variables like left and right which hold the 0 and N-1 indexes. Just need to check that :

  1. Check If the left and right pointer elements are negative then simply increment the left pointer.
  2. Otherwise, if the left element is positive and the right element is negative then simply swap the elements, and simultaneously increment and decrement the left and right pointers.
  3. Else if the left element is positive and the right element is also positive then simply decrement the right pointer.
  4. Repeat the above 3 steps until the left pointer ? right pointer.

Below is the implementation of the above approach:

C++
// C++ program of the above 
// approach

#include <iostream>
using namespace std;

// Function to shift all the
// negative elements on left side
void shiftall(int arr[], int left, 
              int right)
{
  
  // Loop to iterate over the 
  // array from left to the right
  while (left<=right)
  {
    // Condition to check if the left
    // and the right elements are 
    // negative
    if (arr[left] < 0 && arr[right] < 0)
      left+=1;
    
    // Condition to check if the left 
    // pointer element is positive and 
    // the right pointer element is negative
    else if (arr[left]>0 && arr[right]<0)
    {
      int temp=arr[left];
      arr[left]=arr[right];
      arr[right]=temp;
      left+=1;
      right-=1;
    }
    
    // Condition to check if both the 
    // elements are positive
    else if (arr[left]>0 && arr[right] >0)
      right-=1;
    else{
      left += 1;
      right -= 1;
    }
  }
}

// Function to print the array
void display(int arr[], int right){
  
  // Loop to iterate over the element
  // of the given array
  for (int i=0;i<=right;++i){
    cout<<arr[i]<<" ";
  }
  cout<<endl;
}

// Driver Code
int main() 
{
  int arr[] = {-12, 11, -13, -5, 
               6, -7, 5, -3, 11};
  int arr_size = sizeof(arr) / 
                sizeof(arr[0]);
  
  // Function Call
  shiftall(arr,0,arr_size-1);
  display(arr,arr_size-1);
  return 0;
}

//added by Dhruv Goyal
Java
// Java program of the above
// approach
import java.io.*;

class GFG{

// Function to shift all the
// negative elements on left side
static void shiftall(int[] arr, int left,
                     int right)
{
    
    // Loop to iterate over the
    // array from left to the right
    while (left <= right) 
    {
        
        // Condition to check if the left
        // and the right elements are
        // negative
        if (arr[left] < 0 && arr[right] < 0)
            left++;

        // Condition to check if the left
        // pointer element is positive and
        // the right pointer element is negative
        else if (arr[left] > 0 && arr[right] < 0)
        {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }

        // Condition to check if both the
        // elements are positive
        else if (arr[left] > 0 && arr[right] > 0)
            right--;
        else
        {
            left++;
            right--;
        }
    }
}

// Function to print the array
static void display(int[] arr, int right)
{
    
    // Loop to iterate over the element
    // of the given array
    for(int i = 0; i <= right; ++i)
        System.out.print(arr[i] + " ");
        
    System.out.println();
}

// Drive code
public static void main(String[] args)
{
    int[] arr = { -12, 11, -13, -5, 
                   6, -7, 5, -3, 11 };
                   
    int arr_size = arr.length;

    // Function Call
    shiftall(arr, 0, arr_size - 1);
    display(arr, arr_size - 1);
}
}

// This code is contributed by dhruvgoyal267
Python3
# Python3 program of the 
# above approach

# Function to shift all the 
# the negative elements to
# the left of the array
def shiftall(arr,left,right):
  
  # Loop to iterate while the 
  # left pointer is less than
  # the right pointer
  while left<=right:
    
    # Condition to check if the left
    # and right pointer negative
    if arr[left] < 0 and arr[right] < 0:
      left+=1
      
    # Condition to check if the left 
    # pointer element is positive and 
    # the right pointer element is
    # negative
    else if arr[left]>0 and arr[right]<0:
      arr[left], arr[right] = \
              arr[right],arr[left]
      left+=1
      right-=1
      
    # Condition to check if the left
    # pointer is positive and right 
    # pointer as well
    else if arr[left]>0 and arr[right]>0:
      right-=1
    else:
      left+=1
      right-=1
      
# Function to print the array
def display(arr):
  for i in range(len(arr)):
    print(arr[i], end=" ")
  print()

# Driver Code
if __name__ == "__main__":
  arr=[-12, 11, -13, -5, \
       6, -7, 5, -3, 11]
  n=len(arr)
  shiftall(arr,0,n-1)
  display(arr)

# Sumit Singh
C#
// C# program of the above
// approach
using System.IO;
using System;
class GFG
{
    // Function to shift all the
    // negative elements on left side
    static void shiftall(int[] arr, int left,int right)
    {
      
        // Loop to iterate over the
        // array from left to the right
        while (left <= right) 
        {
         
            // Condition to check if the left
            // and the right elements are
            // negative
            if (arr[left] < 0 && arr[right] < 0)
                left++;
 
            // Condition to check if the left
            // pointer element is positive and
            // the right pointer element is negative
            else if (arr[left] > 0 && arr[right] < 0)
            {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
 
            // Condition to check if both the
            // elements are positive
            else if (arr[left] > 0 && arr[right] > 0)
                right--;
            else
            {
                left++;
                right--;
            }
        }
    }
  
    // Function to print the array
    static void display(int[] arr, int right)
    {
      
        // Loop to iterate over the element
        // of the given array
        for(int i = 0; i <= right; ++i)
        {
            Console.Write(arr[i] + " ");
            
        }
        Console.WriteLine();
    }
    
    // Drive code                   
    static void Main()
    {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, 11};
        int arr_size = arr.Length;
        shiftall(arr, 0, arr_size - 1);
        display(arr, arr_size - 1);
    }
}

// This code is contributed by avanitrachhadiya2155
JavaScript
// Javascript program of the above 
// approach

// Function to shift all the
// negative elements on left side
function shiftall(arr, left, right)
{
    
    // Loop to iterate over the 
    // array from left to the right
    while (left <= right)
    {
        
        // Condition to check if the left
        // and the right elements are 
        // negative
        if (arr[left] < 0 && arr[right] < 0)
            left += 1;
        
        // Condition to check if the left 
        // pointer element is positive and 
        // the right pointer element is negative
        else if(arr[left] > 0 && arr[right] < 0)
        {
            let temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left += 1;
            right -= 1;
        }
        
        // Condition to check if both the 
        // elements are positive
        else if (arr[left] > 0 && arr[right] > 0)
            right -= 1;
        else
        {
            left += 1;
            right -= 1;
        }
    }
}

// Function to print the array
function display(arr, right)
{
    
    // Loop to iterate over the element
    // of the given array
    for(let i = 0; i < right; i++)
        console.log(arr[i] + " ");
}

// Driver Code
let arr = [ -12, 11, -13, -5, 
             6, -7, 5, -3, 11 ];
let arr_size = arr.length;

// Function Call
shiftall(arr, 0, arr_size - 1);
display(arr, arr_size);
 
// This code is contributed by annianni

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

This is an in-place rearranging algorithm for arranging the positive and negative numbers where the order of elements is not maintained.
Time Complexity: O(N)
Auxiliary Space: O(1)

The problem becomes difficult if we need to maintain the order of elements. Please refer to Rearrange positive and negative numbers with constant extra space for details.

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeek’s main page and help other Geeks.

Approach 3:
Here, we will use the famous Dutch National Flag Algorithm for two “colors”. The first color will be for all negative integers and the second color will be for all positive integers. We will divide the array into three partitions with the help of two pointers, low and high. 

  1. ar[1…low-1] negative integers
  2. ar[low…high] unknown
  3. ar[high+1…N] positive integers

Now, we explore the array with the help of low pointer, shrinking the unknown partition, and moving elements to their correct partition in the process. We do this until we have explored all the elements, and size of the unknown partition shrinks to zero.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

// Swap Function.
void swap(int &a,int &b){
  int temp =a;
  a=b;
  b=temp;
}
  
// Using Dutch National Flag Algorithm.
void reArrange(int arr[],int n){
      int low =0,high = n-1;
      while(low<high){
      if(arr[low]<0){
          low++;
      }else if(arr[high]>0){
          high--;
      }else{
        swap(arr[low],arr[high]);
      }
    }
}
void displayArray(int arr[],int n){
  for(int i=0;i<n;i++){
    cout<<arr[i]<<" ";
  }
  cout<<endl;
}
int main() {
    // Data
    int arr[] = {1, 2,  -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2,  1};
      int n = sizeof(arr)/sizeof(arr[0]);
      reArrange(arr,n);
    displayArray(arr,n);
    return 0;
}
Java
// Java program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space

public class Gfg {

    // a utility function to swap two elements of an array
    public static void swap(int[] ar, int i, int j)
    {
        int t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }

    // function to shilf all negative integers to the left
    // and all positive integers to the right
    // using Dutch National Flag Algorithm
    public static void move(int[] ar)
    {
        int low = 0;
        int high = ar.length - 1;
        while (low <= high) {
            if (ar[low] <= 0)
                low++;
            else
                swap(ar, low, high--);
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        int[] ar = { 1, 2,  -4, -5, 2, -7, 3,
                     2, -6, -8, -9, 3, 2,  1 };
        move(ar);
        for (int e : ar)
            System.out.print(e + " ");
    }
}

// This code is contributed by Vedant Harshit
Python3
# Python code for the approach

# Using Dutch National Flag Algorithm.
def reArrange(arr, n):
    low,high = 0, n - 1
    while(low<high):
        if(arr[low] < 0):
            low += 1
        elif(arr[high] > 0):
            high -= 1
        else:
            arr[low],arr[high] = arr[high],arr[low]

def displayArray(arr, n):

    for i in range(n):
        print(arr[i],end = " ")
  
    print('')

# driver code
# Data
arr = [1, 2,  -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2,  1]
n = len(arr)
reArrange(arr,n)
displayArray(arr,n)

# This code is contributed by shinjanpatra
C#
// Include namespace system
using System;

// C# program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space
public class Gfg
{
  // a utility function to swap two elements of an array
  public static void swap(int[] ar, int i, int j)
  {
    var t = ar[i];
    ar[i] = ar[j];
    ar[j] = t;
  }
  // function to shilf all negative integers to the left
  // and all positive integers to the right
  // using Dutch National Flag Algorithm
  public static void move(int[] ar)
  {
    var low = 0;
    var high = ar.Length - 1;
    while (low <= high)
    {
      if (ar[low] <= 0)
      {
        low++;
      }
      else 
      {
        Gfg.swap(ar, low, high--);
      }
    }
  }

  // Driver code
  public static void Main(String[] args)
  {
    int[] ar = {1, 2, -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2, 1};
    Gfg.move(ar);
    foreach (int e in ar)
    {            Console.Write(e.ToString() + " ");
    }
  }
}

// This code is contributed by mukulsomukesh
JavaScript
// JavaScript code for the approach

// Using Dutch National Flag Algorithm.
function reArrange(arr, n){
    let low = 0,high = n - 1
    while(low<high){
        if(arr[low] < 0)
            low += 1
        else if(arr[high] > 0)
            high -= 1
        else{
            let temp = arr[low]
            arr[low] = arr[high]
            arr[high] = temp
        }
    }
}

function displayArray(arr, n){

    for(let i = 0; i < n; i++){
        console.log(arr[i]," ")
    }
    console.log('</br>')
}

// driver code
// Data
let arr = [1, 2,  -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2,  1]
let n = arr.length
reArrange(arr,n)
displayArray(arr,n)

// This code is contributed by shinjanpatra

Output
-9 -8 -4 -5 -6 -7 3 2 2 2 1 3 2 1 

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

The order of elements does not matter here. Explanation and code contributed by Vedant Harshit.

Approach 4: Two-Pass Approach

Another approach to move all negative numbers to the beginning and positive numbers to the end of an array with constant extra space is to use a two-pass approach, where we first count the number of negative elements, and then rearrange the elements accordingly.

Steps:

Follow the given steps to solve the problem:

  1. Initialize a variable negCount to count the number of negative elements.
  2. Traverse the array to count the number of negative elements.
  3. Initialize two pointers i and j where i starts from 0 and j starts from negCount.
  4. Iterate through the array using i and j pointers until i is less than negCount and j is less than n.
    • If the element at index i is negative, increment i.
    • If the element at index j is non-negative, increment j.
    • If the element at index i is negative and the element at index j is non-negative, swap the elements at indices i and j.
    • Increment both i and j.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

void rearrange(int arr[], int n) {
    // Count the number of negative elements
    int negCount = 0;

    // Rearrange the elements based on the count of
    // negative elements
    for (int i = 0; i < n; i++) {
        if (arr[i] < 0) {
            negCount++;
        }
    }

    int i = 0;
    int j = negCount;
    while (i < negCount && j < n) {
        if (arr[i] < 0) {
            i++;
        }
        else if (arr[j] >= 0) {
            j++;
        }
        // Swap negative and positive elements
        else {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j++;
        }
    }
}

// Function to print the array
void display(int arr[], int right) {
    // Loop to iterate over the element
    // of the given array
    for (int i = 0; i <= right; ++i)
        cout << arr[i] << " ";

    cout << endl;
}

// Drive code
int main() {
    int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, 11 };

    int arr_size = sizeof(arr) / sizeof(arr[0]);

    // Function Call
    rearrange(arr, arr_size - 1);
    display(arr, arr_size - 1);

    return 0;
}
Java
// Java program of the above approach
import java.io.*;

class GFG {
    static void rearrange(int[] arr, int n)
    {
        // Count the number of negative elements
        int negCount = 0;

        // Rearrange the elements based on the count of
        // negative elements
        for (int i = 0; i < n; i++) {
            if (arr[i] < 0) {
                negCount++;
            }
        }

        int i = 0;
        int j = negCount;
        while (i < negCount && j < n) {
            if (arr[i] < 0) {
                i++;
            }
            else if (arr[j] >= 0) {
                j++;
            }
            // Swap negative and positive elements
            else {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j++;
            }
        }
    }

    // Function to print the array
    static void display(int[] arr, int right)
    {

        // Loop to iterate over the element
        // of the given array
        for (int i = 0; i <= right; ++i)
            System.out.print(arr[i] + " ");

        System.out.println();
    }

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

        int arr_size = arr.length;

        // Function Call
        rearrange(arr, arr_size - 1);
        display(arr, arr_size - 1);
    }
}

// This code is contributed by Susobhan Akhuli
Python3
def rearrange(arr):
    # Count the number of negative elements
    neg_count = sum(1 for x in arr if x < 0)

    # Rearrange the elements based on the count of negative elements
    i = 0
    j = neg_count
    while i < neg_count and j < len(arr):
        if arr[i] < 0:
            i += 1
        elif arr[j] >= 0:
            j += 1
        else:
            # Swap negative and positive elements
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
            j += 1

# Function to print the array
def display(arr):
    print(" ".join(map(str, arr)))

# Driver code
if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, 11]

    # Function Call
    rearrange(arr)
    display(arr)
JavaScript
function rearrange(arr) {
    // Count the number of negative elements
    let negCount = 0;
    const n = arr.length;

    // Rearrange the elements based on the count of negative elements
    for (let i = 0; i < n; i++) {
        if (arr[i] < 0) {
            negCount++;
        }
    }

    let i = 0;
    let j = negCount;
    while (i < negCount && j < n) {
        if (arr[i] < 0) {
            i++;
        } else if (arr[j] >= 0) {
            j++;
        } else {
            // Swap negative and positive elements
            const temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j++;
        }
    }
}

// Function to print the array
function display(arr) {
    // Loop to iterate over the elements of the given array
    for (let i = 0; i < arr.length; ++i) {
        process.stdout.write(arr[i] + " ");
    }
    console.log();
}

// Driver code
function main() {
    const arr = [-12, 11, -13, -5, 6, -7, 5, -3, 11];

    // Function Call
    rearrange(arr);
    display(arr);
}

main();

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

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



Similar Reads

Rearrange positive and negative numbers with constant extra space
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input: [12 11 -13 -5 6 -7 5 -3 -6] Output: [-13 -5 -7 -3 -6 12 11 6 5]R
15+ min read
Move all negative elements to end in order with extra space allowed
Given an unsorted array arr[] of both negative and positive integer. The task is place all negative element at the end of array without changing the order of positive element and negative element. Examples: Input : arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }Output : 1 3 2 11 6 -1 -7 -5 Input : arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}Output : 7 9 10 11 -5 -
11 min read
Javascript Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at
11 min read
Rearrange array in alternating positive &amp; negative items with O(1) extra space | Set 2
Given an array of positive and negative numbers, arrange them in an alternate fashion such that every positive number is followed by negative and vice-versa. Order of elements in output doesn't matter. Extra positive or negative elements should be moved to end. Examples: Input : arr[] = {-2, 3, 4, -1} Output : arr[] = {-2, 3, -1, 4} OR {-1, 3, -2,
15+ min read
Rearrange array in alternating positive &amp; negative items with O(1) extra space | Set 1
Given an array having positive and negative numbers, our task is to arrange them in an alternate fashion such that every positive number is followed by a negative number and vice-versa maintaining the order of appearance. The number of positive and negative numbers need not to be equal. If there are more positive numbers then they have to appear at
14 min read
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substrings of a numberTry It! We have discussed a solution
7 min read
K'th Largest element in BST using constant extra space
Given a binary search tree, task is to find Kth largest element in the binary search tree. Example: Input : k = 3 Root of following BST 10 / \ 4 20 / / \ 2 15 40 Output : 15 The idea is to use Reverse Morris Traversal which is based on Threaded Binary Trees. Threaded binary trees use the NULL pointers to store the successor and predecessor informat
10 min read
Connect nodes at same level using constant extra space
Write a function to connect all the adjacent nodes at the same level in a binary tree. The structure of the given Binary Tree node is like following C/C++ Code struct node{ int data; struct node* left; struct node* right; struct node* nextRight; }; // This code is contributed by Yash Agarwal(yashagarwal2852002) C/C++ Code struct node { int data; st
15+ min read
Sort an array according to absolute difference with a given value "using constant extra space"
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: Input : arr[] = {10,
7 min read
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
Given an unsorted array of distinct numbers, write a function that returns true if array consists of consecutive numbers. Examples : Input : arr[] = {5, 4, 2, 1, 3} Output : Yes Input : arr[] = {2, 1, 0, -3, -1, -2} Output : YesRecommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We have discussed three different app
6 min read
Move all digits to the beginning of a given string
Given a string S, the task is to move all the digits present in the string, to the beginning of the string. Examples: Input: S = “Geeks4forGeeks123”Output: 4123GeeksforGeeksExplanation:The given string contains digits 4, 1, 2, and 3. Moving all the digits to the beginning of the string modifies the string to "4123GeeksforGeeks". Input: S = “Geeksfo
7 min read
Segregating negative and positive maintaining order and O(1) space
Segregation of negative and positive numbers in an array without using extra space, and maintaining insertion order and in O(n^2) time complexity. Examples: Input :9 12 11 -13 -5 6 -7 5 -3 -6 Output :-13 -5 -7 -3 -6 12 11 6 5 Input :5 11 -13 6 -7 5 Output :-13 -7 11 6 5 We have discussed this problem below posts. ers-beginning-positive-end-constant
7 min read
Only integer with positive value in positive negative value in array
Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Output : 8 All positive elements have an equal negativ
8 min read
Find ratio of zeroes, positive numbers and negative numbers in the Array
Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio would be positive: 3/6 = 0.5000, negative: 2/6 = 0.3
7 min read
Rearrange Array in negative numbers, zero and then positive numbers order
Given an arr[ ] of size N, containing positive, negative integers and one zero. The task is to rearrange the array in such a way that all negative numbers are on the left of 0 and all positive numbers are on the right. Note: It is not mandatory to maintain the order of the numbers. If there are multiple possible answers, print any of them. Examples
6 min read
Replace all elements by difference of sums of positive and negative numbers after that element
Given an array of positive and negative elements. The task is to replace every i-th element of the array by the absolute difference of absolute sums of positive and negative elements in the range i+1 to N. That is, find the absolute sum of all positive elements and the absolute sum of all negative elements in the range i+1 to N. Now find the absolu
12 min read
Swap first odd and even valued nodes from the beginning and end of a Linked List
Given a singly Linked List, the task is to swap the first odd valued node from the beginning and the first even valued node from the end of the Linked List. If the list contains node values of a single parity, then no modifications are required. Examples: Input: 4 -&gt; 3 -&gt; 5 -&gt; 2 -&gt; 3 -&gt; NULLOutput: 4 -&gt; 2 -&gt; 5 -&gt; 3 -&gt; 3 -
13 min read
Delete Kth nodes from the beginning and end of a Linked List
Given a singly Linked List and an integer K denoting the position of a Linked List, the task is to delete the Kth node from the beginning and end of the Linked List. Examples: Input: 1 ? 2 ? 3 ? 4 ? 5 ? 6, K = 3Output: 1 ? 2 ? 5 ? 6Explanation: Deleted Nodes : 3, 4 Input: 1 ? 2 ? 3 ? 4 ? 5 ? 6, K = 1Output: 2 ? 3 ? 4 ? 5 Input: 1 ? 2 ? 3 ? 4 ? 5 ?
13 min read
Find the average of k digits from the beginning and l digits from the end of the given number
Given three integers N, K and L. The task is to find the average of the first K digits and the last L digits of the given number N without any digit overlapping.Examples: Input: N = 123456, K = 2, L = 3 Output: 3.0 Sum of first K digits will be 1 + 2 = 3 Sum of last L digits will be 4 + 5 + 6 = 15 Average = (3 + 15) / (2 + 3) = 18 / 5 = 3Input: N =
13 min read
Swap Kth node from beginning with Kth node from end in a Doubly Linked List
Prerequisites: Doubly Linked List Given a doubly-linked list, the task is to swap Kth node from the beginning with Kth node from the ending.Note: Please note here the nodes are swapped and not the data in the nodes. Examples: Input: DLL = 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6, K = 3 Output: 1 2 4 3 5 6 Explanation: Third nod
15+ min read
Swap Kth node from beginning with Kth node from end in a Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details like Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
15+ min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Count frequencies of all elements in array in O(1) extra space and O(n) time
Given an unsorted array of n integers that can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count the frequency of all elements that are present and print the missing elements. Examples: Input: arr[] = {2, 3, 3, 2, 5}Output: Below are frequencies of all elements 1 -
15+ min read
Rearrange positive and negative numbers using inbuilt sort function
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input : arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6] Output : arr[] = [-
15 min read
Lambda expression in Python to rearrange positive and negative numbers
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array. The order of appearance should be maintained. Examples: Input : arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6] Output : arr[] = [-13, -5, -7, -3, -6, 12, 11, 6, 5]\Input : arr[] = [-12, 11, 0, -5, 6, -7, 5
2 min read
Add two numbers represented by Linked List without any extra space
Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list representation of addition of two input numbers. Expected Space Complexity O(1). Examples: Input: L1 = 5 -&gt; 6 -&gt; 3 -&gt; NULL L2 = 8 -&gt; 4 -&gt; 2 -&gt; NULL Output: 1 -&gt; 4 -&gt; 0 -&gt; 5 -&gt; NULL Input: L1 = 1 -&gt;
11 min read
Generate an array with K positive numbers such that arr[i] is either -1 or 1 and sum of the array is positive
Given two positive integers, N and K ( 1 ≤ K ≤ N ), the task is to construct an array arr[](1-based indexing) such that each array element arr[i] is either i or -i and the array contains exactly K positive values such that sum of the array elements is positive. If more than one such sequence can be generated, print any of them. Otherwise, print "-1
7 min read
Print all the pairs that contains the positive and negative values of an element
Given an array of distinct integers, print all the pairs having a positive value and negative value of a number that exists in the array. Note: Order of the pairs doesn't matter. Examples: Input: arr[] = { 1, -3, 2, 3, 6, -1 }Output: -1 1 -3 3Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }Output: -1 1 -4 4 -8 8 -9 9 Naive approach(using two loops) Al
13 min read
Replace all occurrences of string AB with C without using extra space
Given a string str that may contain one more occurrences of "AB". Replace all occurrences of "AB" with "C" in str. Examples: Input : str = "helloABworld"Output : str = "helloCworld"Input : str = "fghABsdfABysu"Output : str = "fghCsdfCysu"A simple solution is to find all occurrences of "AB". For every occurrence, replace it with C and move all chara
10 min read
Practice Tags :
three90RightbarBannerImg