Given an integer array, rearrange it such that it contains positive and negative numbers at alternate positions. If the array contains more positive or negative elements, move them to the end of the array. Assume that all values in the array are non-zero.

For example,

Input:  { 9, -3, 5, -2, -8, -6, 1, 3 }
Output: { 5, -2, 9, -6, 1, -8, 3, -3 }
 
Input:  { 9, -3, 5, -2, -8, -6 }
Output: { 5, -2, 9, -6, -3, -8 }
 
Input:  { 9, -3, 5, -2, 8, 6, 1, 3 }
Output: { 5, -2, 9, -3, 8, 6, 1, 3 }

Practice this problem

We can solve this problem in linear time by using the partitioning logic of Quicksort. The idea is to use 0 as a pivot element and make one pass of the partition process. The resultant array will contain all positive integers to the end of the array and all negative integers at the beginning. Then swap alternate negative elements from the next available positive element until the end of the array is reached, or all negative or positive integers are exhausted.

Following is the implementation of the above approach in C++, Java, and Python:

C++


Download  Run Code

Output:

5 -2 9 -6 1 -8 3 -3

Java


Download  Run Code

Output:

[5, -2, 9, -6, 1, -8, 3, -3]

Python


Download  Run Code

Output:

[5, -2, 9, -6, 1, -8, 3, -3]

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input. The problem with this approach is that it changes the relative order of elements.

 
Exercise: Implement a solution that preserves the relative order of elements.