Problem
Given an array, rearrange it so that all positive numbers are on one side and all negative numbers are on the other side, without changing the relative order of the positive and negative numbers.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Use positive and negative lists
Here is the approach:
- Two-pass Algorithm:
- Perform the rearrangement in two passes.
- Separate Positive and Negative Numbers:
- Use two arrays or lists to separately store the positive and negative numbers during the first pass.
- Combine Arrays:
- In the second pass, combine both arrays by appending all positive numbers first, followed by all negative numbers
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of elements in the array, since we traverse the array two times. - 🧺 Space complexity:
O(n)
, for storing the separated positive and negative numbers in auxiliary arrays or lists.
Method 2 - Divide and Conquer
This approach resembles merge sort. Divide the array into two halves, solve each half individually, and then merge them. The merging step is tricky. Here’s the logic for merging (negative numbers on the left and positives on the right):
- Traverse the left half of the array until you find a positive integer, then reverse the array after that point (calling this part ‘A’).
- Traverse the right half of the array until you find a positive integer, then reverse the array before that point (calling this part ‘B’).
- Finally, reverse both parts ‘A’ and ‘B’. Refer to the example for a better understanding.
Code
|
|
|
|
Method 3 - Quicksort Partition
Here is the approach:
- Partition the array: Use a partitioning method similar to QuickSort to move all negative numbers to the left and all positive numbers to the right while maintaining their relative order.
- Merging in Alternating Order: After partitioning, the array will have all negative elements on one side and all positive elements on the other side.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)