Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
Last Updated :
06 Sep, 2023
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 the end of the array , same condition for negative numbers also .
Examples:
Input: arr[] = {1, 2, 3, -4, -1, 4}
Output: arr[] = {-4, 1, -1, 2, 3, 4}
Input: arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}
Output: arr[] = {-5, 5, -2, 2, -8, 4, 7, 1, 8, 0}
This question has been asked in many places (See this and this)
Naïve Approach: To solve the problem follow the below idea:
- The problem can be easily solved if O(n) extra space is allowed.
- We can store the positive values and negative values in two separate data structures.
- We will start filling the original array with alternating negative and positive values in the same order
in which it appears in the original array.
It becomes interesting due to the limitations that O(1) extra space and order of appearances.
Optimal Approach: To solve the problem in O(1) Auxiliary space follow the below idea:
The idea is to process the array from left to right. While processing, find the first out-of-place element in the remaining unprocessed array. An element is out of place if it is negative and at odd index (0-based index), or if it is positive and at even index (0-based index). Once we find an out-of-place element, we find the first element after it with an opposite sign. We right rotate the subarray between these two elements (including these two).
Illustration:
Let the array be arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }
First iteration:
- { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 } , -2 appears on odd index position and is out of place.
We will look for the first element that appears with an opposite sign
- { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 } => perform rotation of subarray between this two elements
- { -5, 5, -2, 2, 4, 7, 1, 8, 0, -8 }
Second iteration:
- { -5, 5, -2, 2, 4, 7, 1, 8, 0, -8 } , 4 is out of place.
- { -5, 5, -2, 2, 4, 7, 1, 8, 0, -8 } => -8 is of different sign
- { -5, 5, -2, 2, -8, 4, 7, 1, 8, 0 } => after performing right rotation between 4 to -8
resultant array arr[] = { -5, 5, -2, 2, -8, 4, 7, 1, 8, 0 }
Follow the steps to solve the problem:
- Maintain a variable to mark if the element is in its correct position or not. Let the variable be outofplace. Initially, it is -1.
- We will iterate over the array.
- If outofplace is -1, we will check if the current index is out of place.
- If the current index is out of place we will update the outofplace with the index value.
- Else we will keep the value as it is.
- If the outofplace is not -1, we will search for the next index which has a different sign than that of the value that is present in outofplace position.
- Now we will pass this two positions to right rotate our array.
- Update the value of outofplace by 2 unit (becuase previously valid elements will now become the out-of-place elements).
Following is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
void rightrotate( int arr[], int n, int outofplace, int cur)
{
char tmp = arr[cur];
for ( int i = cur; i > outofplace; i--)
arr[i] = arr[i - 1];
arr[outofplace] = tmp;
}
void rearrange( int arr[], int n)
{
int outofplace = -1;
for ( int index = 0; index < n; index++) {
if (outofplace >= 0) {
if (((arr[index] >= 0) && (arr[outofplace] < 0))
|| ((arr[index] < 0)
&& (arr[outofplace] >= 0))) {
rightrotate(arr, n, outofplace, index);
if (index - outofplace >= 2)
outofplace = outofplace + 2;
else
outofplace = -1;
}
}
if (outofplace == -1) {
if (((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01))) {
outofplace = index;
}
}
}
}
void printArray( int arr[], int n)
{
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
cout << endl;
}
int main()
{
int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Given array is \n" ;
printArray(arr, n);
rearrange(arr, n);
cout << "Rearranged array is \n" ;
printArray(arr, n);
return 0;
}
|
Java
import java.io.*;
class RearrangeArray {
void rightrotate( int arr[], int n, int outofplace,
int cur)
{
int tmp = arr[cur];
for ( int i = cur; i > outofplace; i--)
arr[i] = arr[i - 1 ];
arr[outofplace] = tmp;
}
void rearrange( int arr[], int n)
{
int outofplace = - 1 ;
for ( int index = 0 ; index < n; index++) {
if (outofplace >= 0 ) {
if (((arr[index] >= 0 )
&& (arr[outofplace] < 0 ))
|| ((arr[index] < 0 )
&& (arr[outofplace] >= 0 ))) {
rightrotate(arr, n, outofplace, index);
if (index - outofplace >= 2 )
outofplace = outofplace + 2 ;
else
outofplace = - 1 ;
}
}
if (outofplace == - 1 ) {
if (((arr[index] >= 0 )
&& ((index & 0x01 ) == 0 ))
|| ((arr[index] < 0 )
&& (index & 0x01 ) == 1 ))
outofplace = index;
}
}
}
void printArray( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
System.out.println( "" );
}
public static void main(String[] args)
{
RearrangeArray rearrange = new RearrangeArray();
int arr[] = { - 5 , - 2 , 5 , 2 , 4 , 7 , 1 , 8 , 0 , - 8 };
int n = arr.length;
System.out.println( "Given array is " );
rearrange.printArray(arr, n);
rearrange.rearrange(arr, n);
System.out.println( "RearrangeD array is " );
rearrange.printArray(arr, n);
}
}
|
Python
def rightRotate(arr, n, outOfPlace, cur):
temp = arr[cur]
for i in range (cur, outOfPlace, - 1 ):
arr[i] = arr[i - 1 ]
arr[outOfPlace] = temp
return arr
def rearrange(arr, n):
outOfPlace = - 1
for index in range (n):
if (outOfPlace > = 0 ):
if ((arr[index] > = 0 and arr[outOfPlace] < 0 ) or
(arr[index] < 0 and arr[outOfPlace] > = 0 )):
arr = rightRotate(arr, n, outOfPlace, index)
if (index - outOfPlace > 2 ):
outOfPlace + = 2
else :
outOfPlace = - 1
if (outOfPlace = = - 1 ):
if ((arr[index] > = 0 and index % 2 = = 0 ) or
(arr[index] < 0 and index % 2 = = 1 )):
outOfPlace = index
return arr
arr = [ - 5 , - 2 , 5 , 2 , 4 ,
7 , 1 , 8 , 0 , - 8 ]
print ( "Given Array is:" )
print (arr)
print ( "\nRearranged array is:" )
print (rearrange(arr, len (arr)))
|
C#
using System;
class GFG {
static void rightrotate( int [] arr, int n,
int outofplace, int cur)
{
int tmp = arr[cur];
for ( int i = cur; i > outofplace; i--)
arr[i] = arr[i - 1];
arr[outofplace] = tmp;
}
static void rearrange( int [] arr, int n)
{
int outofplace = -1;
for ( int index = 0; index < n; index++) {
if (outofplace >= 0) {
if (((arr[index] >= 0)
&& (arr[outofplace] < 0))
|| ((arr[index] < 0)
&& (arr[outofplace] >= 0))) {
rightrotate(arr, n, outofplace, index);
if (index - outofplace > 2)
outofplace = outofplace + 2;
else
outofplace = -1;
}
}
if (outofplace == -1) {
if (((arr[index] >= 0)
&& ((index & 0x01) == 0))
|| ((arr[index] < 0)
&& (index & 0x01) == 1))
outofplace = index;
}
}
}
static void printArray( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
Console.WriteLine( "" );
}
public static void Main()
{
int [] arr = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 };
int n = arr.Length;
Console.WriteLine( "Given array is " );
printArray(arr, n);
rearrange(arr, n);
Console.WriteLine( "RearrangeD array is " );
printArray(arr, n);
}
}
|
Javascript
<script>
function rightrotate(arr , n , outofplace , cur) {
var tmp = arr[cur];
for (i = cur; i > outofplace; i--)
arr[i] = arr[i - 1];
arr[outofplace] = tmp;
}
function rearrange(arr , n) {
var outofplace = -1;
for ( var index = 0; index < n; index++)
{
if (outofplace >= 0)
{
if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) {
rightrotate(arr, n, outofplace, index);
if (index - outofplace >= 2)
outofplace = outofplace + 2;
else
outofplace = -1;
}
}
if (outofplace == -1) {
if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1))
outofplace = index;
}
}
}
function printArray(arr , n) {
for (i = 0; i < n; i++)
document.write(arr[i] + " " );
document.write( "" );
}
var arr = [ -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 ];
var n = arr.length;
document.write( "Given array is " );
printArray(arr, n);
rearrange(arr, n);
document.write( "<br/>Rearranged array is " );
printArray(arr, n);
</script>
|
PHP
<?php
function rightrotate(& $arr , $n ,
$outofplace , $cur )
{
$tmp = $arr [ $cur ];
for ( $i = $cur ; $i > $outofplace ; $i --)
$arr [ $i ] = $arr [ $i - 1];
$arr [ $outofplace ] = $tmp ;
}
function rearrange(& $arr , $n )
{
$outofplace = -1;
for ( $index = 0; $index < $n ; $index ++)
{
if ( $outofplace >= 0)
{
if ((( $arr [ $index ] >= 0) && ( $arr [ $outofplace ] < 0)) ||
(( $arr [ $index ] < 0) && ( $arr [ $outofplace ] >= 0)))
{
rightrotate( $arr , $n , $outofplace , $index );
if ( $index - $outofplace > 2)
$outofplace = $outofplace + 2;
else
$outofplace = -1;
}
}
if ( $outofplace == -1)
{
if ((( $arr [ $index ] >= 0) && (!( $index & 0x01)))
|| (( $arr [ $index ] < 0) && ( $index & 0x01)))
{
$outofplace = $index ;
}
}
}
}
function printArray(& $arr , $n )
{
for ( $i = 0; $i < $n ; $i ++)
echo $arr [ $i ]. " " ;
echo "\n" ;
}
$arr = array (-5, -2, 5, 2, 4, 7, 1, 8, 0, -8);
$n = sizeof( $arr );
echo "Given array is \n" ;
printArray( $arr , $n );
rearrange( $arr , $n );
echo "Rearranged array is \n" ;
printArray( $arr , $n );
?>
|
Output
Given array is
-5 -2 5 2 4 7 1 8 0 -8
Rearranged array is
-5 5 -2 2 -8 4 7 1 8 0
Time Complexity: O(N^2), as we are using a loop to traverse N times and calling function to right rotate each time which will cost O (N).
Auxiliary Space: O(1).
Related article:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...