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 the end of the array.
For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the output should be [9, -7, 8, -3, 5, -1, 2, 4, 6]
Note: The partition process changes relative order of elements. I.e. the order of the appearance of elements is not maintained with this approach. See this for maintaining order of appearance of elements in this problem.
The solution is to first separate positive and negative numbers using partition process of QuickSort. In the partition process, consider 0 as value of pivot element so that all negative numbers are placed before positive numbers. Once negative and positive numbers are separated, we start from the first negative number and first positive number, and swap every alternate negative number with next positive number.
4 -3 5 -1 6 -7 2 8 9
Time Complexity: O(n) where n is number of elements in given array.
Auxiliary Space: O(1)
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
- Rearrange positive and negative numbers with constant extra space
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
- Move all negative numbers to beginning and positive to end with constant extra space
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
- Rearrange positive and negative numbers using inbuilt sort function
- Lambda expression in Python to rearrange positive and negative numbers
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
- Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)
- Move all negative elements to end in order with extra space allowed
- Segregating negative and positive maintaining order and O(1) space
- Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
- Find duplicates in O(n) time and O(1) extra space | Set 1
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Count frequencies of all elements in array in O(1) extra space and O(n) time