Rearrange positive and negative numbers with constant extra space

Hello Everyone,

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 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]

A simple solution is to use another array. We copy all elements of original array to new array. We then traverse the new array and copy all negative and positive elements back in original array one by one. The problem with this approach is that it uses auxiliary array and we’re not allowed to use any data structure to solve this problem.
One approach that does not use any data structure is to use use partition process of QuickSort. The idea is to consider 0 as pivot and divide the array around it. The problem with this approach is that it changes relative order of elements.

Let’s now discuss few methods which do not use any other data structure and also preserves relative order of elements.

We can modify insertion sort to solve this problem.
Algorithm –

Loop from i = 1 to n - 1. a) If the current element is positive, do nothing. b) If the current element arr[i] is negative, we insert it into sequence arr[0…i-1] such that all positive elements in arr[0…i-1] are shifted one position to their right and arr[i] is inserted at index of first positive element.

Below is the implementation –

// C++ program to Rearrange positive and negative

// numbers in a array

#include <stdio.h>

// A utility function to print an array of size n

void printArray( int arr[], int n)

{

for ( int i = 0; i < n; i++)

printf ( "%d " , arr[i]);

printf ( "\n" );

}

// Function to Rearrange positive and negative

// numbers in a array

void RearrangePosNeg( int arr[], int n)

{

int key, j;

for ( int i = 1; i < n; i++) {

key = arr[i];

// if current element is positive

// do nothing

if (key > 0)

continue ;

/* if current element is negative,

shift positive elements of arr[0..i-1],

to one position to their right */

j = i - 1;

while (j >= 0 && arr[j] > 0) {

arr[j + 1] = arr[j];

j = j - 1;

}

// Put negative element at its right position

arr[j + 1] = key;

}

}

/* Driver program to test above functions */

int main()

{

int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };

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

RearrangePosNeg(arr, n);

printArray(arr, n);

return 0;

}

Output

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

Time complexity of above solution is O(n2) and auxiliary space is O(1). We have maintained the order of appearance and have not used any other data structure.

Approach 2: Optimized Merge Sort

Merge method of standard merge sort algorithm can be modified to solve this problem. While merging two sorted halves say left and right, we need to merge in such a way that negative part of left and right sub-array is copied first followed by positive part of left and right sub-array.

Below is the implementation of the idea –

// C++ program to Rearrange positive and negative

// numbers in a array

#include <iostream>

using namespace std;

/* Function to print an array */

void printArray( int A[], int size)

{

for ( int i = 0; i < size; i++)

cout << A[i] << " " ;

cout << endl;

}

// Merges two subarrays of arr[].

// First subarray is arr[l..m]

// Second subarray is arr[m+1..r]

void merge( int arr[], int l, int m, int r)

{

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

/* create temp arrays */

int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */

for (i = 0; i < n1; i++)

L[i] = arr[l + i];

for (j = 0; j < n2; j++)

R[j] = arr[m + 1 + j];

/* Merge the temp arrays back into arr[l..r]*/

i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

// Note the order of appearance of elements should

// be maintained - we copy elements of left subarray

// first followed by that of right subarray

// copy negative elements of left subarray

while (i < n1 && L[i] < 0)

arr[k++] = L[i++];

// copy negative elements of right subarray

while (j < n2 && R[j] < 0)

arr[k++] = R[j++];

// copy positive elements of left subarray

while (i < n1)

arr[k++] = L[i++];

// copy positive elements of right subarray

while (j < n2)

arr[k++] = R[j++];

}

// Function to Rearrange positive and negative

// numbers in a array

void RearrangePosNeg( int arr[], int l, int r)

{

if (l < r) {

// Same as (l + r)/2, but avoids overflow for

// large l and h

int m = l + (r - l) / 2;

// Sort first and second halves

RearrangePosNeg(arr, l, m);

RearrangePosNeg(arr, m + 1, r);

merge(arr, l, m, r);

}

}

/* Driver program to test above functions */

int main()

{

int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };

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

RearrangePosNeg(arr, 0, arr_size - 1);

printArray(arr, arr_size);

return 0;

}

Output

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

The time complexity of above solution is O(n log n).

Let Ln and Lp denotes the negative part and positive part of left sub-array respectively. Similarly, Rn and Rp denote the negative and positive part of right sub-array respectively.

Below are the steps to convert [Ln Lp Rn Rp] to [Ln Rn Lp Rp] without using extra space.

  1. Reverse Lp and Rn. We get [Lp] -> [Lp’] and [Rn] -> [Rn’] [Ln Lp Rn Rp] -> [Ln Lp’ Rn’ Rp] 2. Reverse [Lp’ Rn’]. We get [Rn Lp]. [Ln Lp’ Rn’ Rp] -> [Ln Rn Lp Rp]

Below is the implementation of above idea –

// C++ program to Rearrange positive and negative

// numbers in a array

#include <bits/stdc++.h>

using namespace std;

/* Function to print an array */

void printArray( int A[], int size)

{

for ( int i = 0; i < size; i++)

cout << A[i] << " " ;

cout << endl;

}

/* Function to reverse an array. An array can be

reversed in O(n) time and O(1) space. */

void reverse( int arr[], int l, int r)

{

if (l < r) {

swap(arr[l], arr[r]);

reverse(arr, ++l, --r);

}

}

// Merges two subarrays of arr[].

// First subarray is arr[l..m]

// Second subarray is arr[m+1..r]

void merge( int arr[], int l, int m, int r)

{

int i = l; // Initial index of 1st subarray

int j = m + 1; // Initial index of IInd

while (i <= m && arr[i] < 0)

i++;

// arr[i..m] is positive

while (j <= r && arr[j] < 0)

j++;

// arr[j..r] is positive

// reverse positive part of

// left sub-array (arr[i..m])

reverse(arr, i, m);

// reverse negative part of

// right sub-array (arr[m+1..j-1])

reverse(arr, m + 1, j - 1);

// reverse arr[i..j-1]

reverse(arr, i, j - 1);

}

// Function to Rearrange positive and negative

// numbers in a array

void RearrangePosNeg( int arr[], int l, int r)

{

if (l < r) {

// Same as (l+r)/2, but avoids overflow for

// large l and h

int m = l + (r - l) / 2;

// Sort first and second halves

RearrangePosNeg(arr, l, m);

RearrangePosNeg(arr, m + 1, r);

merge(arr, l, m, r);

}

}

/* Driver code */

int main()

{

int arr[] = { -12, 11, -13, -5,

6, -7, 5, -3, -6 };

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

RearrangePosNeg(arr, 0, arr_size - 1);

printArray(arr, arr_size);

return 0;

}

The time complexity of above solution is O(n log n), O(Log n) space for recursive calls, and no additional data structure.

Approach 4: Using Two Pointer Algorithm

// C++ implementation of the above approach

#include <iostream>

using namespace std;

void RearrangePosNeg( int arr[], int n)

{

int i = 0;

int j = n - 1;

while ( true ) {

// Loop until arr[i] < 0 and

// still inside the array

while (arr[i] < 0 && i < n)

i++;

// Loop until arr[j] > 0 and

// still inside the array

while (arr[j] > 0 && j >= 0)

j--;

// if i is less than j

if (i < j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

}

else

break ;

}

}

// Driver Code

int main()

{

int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };

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

RearrangePosNeg(arr, n);

for ( int i = 0; i < n; i++)

cout << arr[i] << " " ;

return 0;

}

Output

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