Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
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 maintaining the order of appearance.
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 the end of the array.
Examples :
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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 at many places (See this and this)
Naive Approach :
The above problem can be easily solved if O(n) extra space is allowed. It becomes interesting due to the limitations that O(1) extra space and order of appearances.
The idea is to process 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, or it is positive and at even index. Once we find an out of place element, we find the first element after it with opposite sign. We right rotate the subarray between these two elements (including these two).
Following is the implementation of above idea.
C++
/* C++ program to rearrange positive and negative integers in alternate fashion while keeping the order of positive and negative numbers. */#include <assert.h>#include <iostream>using namespace std;// Utility function to right rotate all elements between// [outofplace, cur]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) { // find the item which must be moved into the // out-of-place entry if out-of-place entry is // positive and current entry is negative OR if // out-of-place entry is negative and current // entry is negative then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 steps // ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && (!(index & 0x01))) || ((arr[index] < 0) && (index & 0x01))) { outofplace = index; } } }}// A utility function to print an array 'arr[]' of size 'n'void printArray(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl;}// Driver codeint 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
class RearrangeArray{ // Utility function to right rotate all elements // between [outofplace, cur] 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) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr[]' of size 'n' void printArray(int arr[], int n) { for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); System.out.println(""); } // Driver Code public static void main(String[] args) { RearrangeArray rearrange = new RearrangeArray(); /* int arr[n] = {-5, 3, 4, 5, -6, -2, 8, 9, -1, -4}; int arr[] = {-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4}; int arr[] = {5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4}; int arr[] = {-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4};*/ 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); }}// This code has been contributed by Mayank Jaiswal |
Python
# Python3 program to rearrange# positive and negative integers# in alternate fashion and# maintaining the order of positive# and negative numbers# rotates the array to right by once# from index 'outOfPlace to cur'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 arrdef rearrange(arr, n): outOfPlace = -1 for index in range(n): if(outOfPlace >= 0): # if element at outOfPlace place in # negative and if element at index # is positive we can rotate the # array to right or if element # at outOfPlace place in positive and # if element at index is negative we # can rotate the array to right 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): # conditions for A[index] to # be in out of place if((arr[index] >= 0 and index % 2 == 0) or (arr[index] < 0 and index % 2 == 1)): outOfPlace = index return arr# Driver Codearr = [-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)))# This code is contributed# by Charan Sai |
C#
// Rearrange array in alternating positive// & negative items with O(1) extra spaceusing System;class GFG { // Utility function to right rotate // all elements between [outofplace, cur] 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) { // find the item which must be moved // into the out-of-place entry if out-of- // place entry is positive and current // entry is negative OR if out-of-place // entry is negative and current entry // is negative then right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry // is now 2 steps ahead if (index - outofplace > 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print an // array 'arr[]' of size 'n' static void printArray(int[] arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); Console.WriteLine(""); } // Driver code 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); }}// This code is contributed by Sam007 |
PHP
<?php// PHP program to rearrange positive and// negative integers in alternate fashion// while keeping the order of positive// and negative numbers.// Utility function to right rotate all// elements between [outofplace, cur]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) { // find the item which must be moved // into the out-of-place entry if // out-of-place entry is positive and // current entry is negative OR if // out-of-place entry is negative // and current entry is negative then // right rotate // [...-3, -4, -5, 6...] --> [...6, -3, -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if ((($arr[$index] >= 0) && ($arr[$outofplace] < 0)) || (($arr[$index] < 0) && ($arr[$outofplace] >= 0))) { rightrotate($arr, $n, $outofplace, $index); // the new out-of-place entry is // now 2 steps ahead if ($index - $outofplace > 2) $outofplace = $outofplace + 2; else $outofplace = -1; } } // if no entry has been flagged out-of-place if ($outofplace == -1) { // check if current entry is out-of-place if ((($arr[$index] >= 0) && (!($index & 0x01))) || (($arr[$index] < 0) && ($index & 0x01))) { $outofplace = $index; } } }}// A utility function to print an// array 'arr[]' of size 'n'function printArray(&$arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i]." "; echo "\n";}// Driver Code// arr = array(-5, 3, 4, 5, -6, -2, 8, 9, -1, -4);// arr = array(-5, -3, -4, -5, -6, 2 , 8, 9, 1 , 4);// arr = array(5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4);// arr = array(-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4);$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);// This code is contributed by ChitraNayal?> |
Javascript
<script> // Utility function to right rotate all elements // between [outofplace, cur] 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) { // find the item which must be moved into // the out-of-place entry if out-of-place // entry is positive and current entry is // negative OR if out-of-place entry is // negative and current entry is negative // then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, // -4, -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 // steps ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && ((index & 0x01) == 0)) || ((arr[index] < 0) && (index & 0x01) == 1)) outofplace = index; } } } // A utility function to print // an array 'arr' of size 'n' function printArray(arr , n) { for (i = 0; i < n; i++) document.write(arr[i] + " "); document.write(""); } // Driver Code /* * var arr[n] = [-5, 3, 4, 5, -6, -2, 8, 9, -1, -4]; var arr = [-5, -3, -4, * -5, -6, 2 , 8, 9, 1 , 4]; var arr = [5, 3, 4, 2, 1, -2 , -8, -9, -1 , -4]; * var arr = [-5, 3, -4, -7, -1, -2 , -8, -9, 1 , -4]; */ 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); // This code is contributed by gauravrajput1</script> |
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)
Space Complexity : O(1)
Efficient Approach :
We first sort the array in non-increasing order.Then we will count the number of positive and negative integers. Then we will swap the one negative and one positive
number till we reach our condition. This will rearrange the array elements because we are sorting the array and accessing the element from left to right according to our need.
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // function which works in the condition when number of // negative numbers are lesser or equal than positive // numbers void fill1(int a[], int neg, int pos) { if (neg % 2 == 1) { for (int i = 1; i < neg; i += 2) { int c = a[i]; int d = a[i + neg]; int temp = c; a[i] = d; a[i + neg] = temp; } } else { for (int i = 1; i <= neg; i += 2) { int c = a[i]; int d = a[i + neg - 1]; int temp = c; a[i] = d; a[i + neg - 1] = temp; } } } // function which works in the condition when number of // negative numbers are greater than positive numbers void fill2(int a[], int neg, int pos) { if (pos % 2 == 1) { for (int i = 1; i < pos; i += 2) { int c = a[i]; int d = a[i + pos]; int temp = c; a[i] = d; a[i + pos] = temp; } } else { for (int i = 1; i <= pos; i += 2) { int c = a[i]; int d = a[i + pos - 1]; int temp = c; a[i] = d; a[i + pos - 1] = temp; } } } void reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void print(int a[], int n) { for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; }// Driver Codeint main(){ // Given array int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = sizeof(arr) / sizeof(arr[0]); int neg = 0, pos = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) neg++; else pos++; } // Sort the array sort(arr, arr + n); if (neg <= pos) { fill1(arr, neg, pos); } else { // reverse the array in this condition reverse(arr, n); fill2(arr, neg, pos); } print(arr, n); return 0;}// This code is contributed by splevel62. |
Java
// Below is the implementation of the above approachimport java.io.*;import java.lang.*;import java.util.*;public class Main { // function which works in the condition when number of // negative numbers are lesser or equal than positive // numbers static void fill1(int a[], int neg, int pos) { if (neg % 2 == 1) { for (int i = 1; i < neg; i += 2) { int c = a[i]; int d = a[i + neg]; int temp = c; a[i] = d; a[i + neg] = temp; } } else { for (int i = 1; i <= neg; i += 2) { int c = a[i]; int d = a[i + neg - 1]; int temp = c; a[i] = d; a[i + neg - 1] = temp; } } } // function which works in the condition when number of // negative numbers are greater than positive numbers static void fill2(int a[], int neg, int pos) { if (pos % 2 == 1) { for (int i = 1; i < pos; i += 2) { int c = a[i]; int d = a[i + pos]; int temp = c; a[i] = d; a[i + pos] = temp; } } else { for (int i = 1; i <= pos; i += 2) { int c = a[i]; int d = a[i + pos - 1]; int temp = c; a[i] = d; a[i + pos - 1] = temp; } } } static void reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void print(int a[], int n) { for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } public static void main(String[] args) throws java.lang.Exception { // Given array int[] arr = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.length; int neg = 0, pos = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) neg++; else pos++; } // Sort the array Arrays.sort(arr); if (neg <= pos) { fill1(arr, neg, pos); } else { // reverse the array in this condition reverse(arr, n); fill2(arr, neg, pos); } print(arr, n); }} |
Python3
# Below is the implementation of the above approachdef rearrange(arr, n): # sort the array arr.sort() # initialize two pointers # one pointing to the negative number # one pointing to the positive number i, j = 1, 1 while j < n: if arr[j] > 0: break j += 1 # swap the numbers until the given condition gets satisfied while (arr[i] < 0) and (j < n): # swaping arr[i], arr[j] = arr[j], arr[i] # increment i by 2 # because a negative number is followed by a positive number i += 2 j += 1 return(arr) # Driver Code# Given arrayarr = [-5, -2, 5, 2, 4, 7, 1, 8, 0, -8]ans = rearrange(arr, len(arr))for num in ans: print(num, end = " ")# This code is contributed by Tharun Reddy |
C#
// Below is the implementation of the above approachusing System;public class GFG { // function which works in the condition when number of // negative numbers are lesser or equal than positive // numbers static void fill1(int []a, int neg, int pos) { if (neg % 2 == 1) { for (int i = 1; i < neg; i += 2) { int c = a[i]; int d = a[i + neg]; int temp = c; a[i] = d; a[i + neg] = temp; } } else { for (int i = 1; i <= neg; i += 2) { int c = a[i]; int d = a[i + neg - 1]; int temp = c; a[i] = d; a[i + neg - 1] = temp; } } } // function which works in the condition when number of // negative numbers are greater than positive numbers static void fill2(int []a, int neg, int pos) { if (pos % 2 == 1) { for (int i = 1; i < pos; i += 2) { int c = a[i]; int d = a[i + pos]; int temp = c; a[i] = d; a[i + pos] = temp; } } else { for (int i = 1; i <= pos; i += 2) { int c = a[i]; int d = a[i + pos - 1]; int temp = c; a[i] = d; a[i + pos - 1] = temp; } } } static void reverse(int []a, int n) { int i, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void print(int []a, int n) { for (int i = 0; i < n; i++) Console.Write(a[i] + " "); Console.WriteLine(); } public static void Main(String[] args) { // Given array int[] arr = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = arr.Length; int neg = 0, pos = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) neg++; else pos++; } // Sort the array Array.Sort(arr); if (neg <= pos) { fill1(arr, neg, pos); } else { // reverse the array in this condition reverse(arr, n); fill2(arr, neg, pos); } print(arr, n); }}// This code is contributed by gauravrajput1 |
Javascript
<script>// Below is the implementation of the above approach // function which works in the condition when number of // negative numbers are lesser or equal than positive // numbers function fill1(a , neg , pos) { if (neg % 2 == 1) { for (var i = 1; i < neg; i += 2) { var c = a[i]; var d = a[i + neg]; var temp = c; a[i] = d; a[i + neg] = temp; } } else { for (var i = 1; i <= neg; i += 2) { var c = a[i]; var d = a[i + neg - 1]; var temp = c; a[i] = d; a[i + neg - 1] = temp; } } } // function which works in the condition when number of // negative numbers are greater than positive numbers function fill2(a , neg , pos) { if (pos % 2 == 1) { for (var i = 1; i < pos; i += 2) { var c = a[i]; var d = a[i + pos]; var temp = c; a[i] = d; a[i + pos] = temp; } } else { for (var i = 1; i <= pos; i += 2) { var c = a[i]; var d = a[i + pos - 1]; var temp = c; a[i] = d; a[i + pos - 1] = temp; } } } function reverse(a , n) { var i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } function print(a , n) { for (var i = 0; i < n; i++) document.write(a[i] + " "); document.write(); } // Given array var arr = [ -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 ]; var n = arr.length; var neg = 0, pos = 0; for (i = 0; i < n; i++) { if (arr[i] < 0) neg++; else pos++; } // Sort the array arr.sort((a,b)=>a-b); if (neg <= pos) { fill1(arr, neg, pos); } else { // reverse the array in this condition reverse(arr, n); fill2(arr, neg, pos); } print(arr, n);// This code is contributed by gauravrajput1</script> |
-8 1 -2 0 -5 2 4 5 7 8
Time Complexity: O(N*logN)
Space Complexity: O(1)
Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
This article is contributed by Sandeep Joshi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



