Alternate Positives and Negatives
Problem
The array has the same number of positive and negative numbers (and no zero). Rearrange it so the signs alternate, starting with a positive number. The positive numbers must keep their original order, and so must the negative numbers. Print the new array.
Constraints
- 2 <= n <= 10^5
- n is even
- no zeros
Examples
Input
6 3 1 -2 -5 2 -4
Output
3 -2 1 -5 2 -4
Solutions
The final place of every number is known: positives take the even places in order, negatives take the odd places in order. A single pass with two write positions is enough.
/*
* Problem : Alternate the signs.
* Input : n and the numbers.
* Output : The new array.
* Approach: Place by index
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: Positive numbers go to the even places 0, 2, 4, ... and negative numbers to the odd places 1, 3, 5, ...
int[] result = new int[a.length];
int positiveAt = 0;
int negativeAt = 1;
// Step 2: One pass from left to right keeps the order of each group.
for (int value : a) {
if (value > 0) {
result[positiveAt] = value;
positiveAt += 2;
} else {
result[negativeAt] = value;
negativeAt += 2;
}
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Where does the 3rd positive number go?