Problem
Given an array nums[]
containing negative and positive elements, rearrange the array such that positive and negative elements occupy alternate positions. If there are extra positive or negative elements, append them to the end of the array.
Examples
Example 1:
|
|
Example 2:
|
|
Similar Problem
This problem is similar to Rearrange Array Elements by Sign, but here we have to do in-place, and there we can return a newly created array as output.
Solution
Method 1 - Naive
- Create two lists: one for positive elements and one for negative elements.
- Use a loop to alternate between positive and negative elements, appending any remaining elements at the end.
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)
Method 2 - Quicksort Partition
Here is the approach:
- Partitioning:
- Use the QuickSort partition logic with
pivot
as0
to partition the array into two halves: all negative numbers on the left side and all positive numbers on the right side.
- Use the QuickSort partition logic with
- Merging in Alternating Order:
- After partitioning, merge the two halves by interleaving one negative and one positive element. Append the remaining elements if any side has more elements.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(1)