Partition into Even and Odd
Problem
Print two lines. The first line is evens: followed by the even numbers in the original order. The second line is odds: followed by the odd numbers in the original order. Negative numbers are possible (-3 is odd).
Constraints
- 1 <= n <= 10^5
Examples
Input
5 1 2 3 4 5
Output
evens: 2 4 odds: 1 3 5
Solutions
One test, two groups. In Java, the test value % 2 == 1 is wrong for negative odd numbers (-3 % 2 is -1), so we test for equality with 0 instead.
/*
* Problem : Split numbers.
* Input : n, then n integers.
* Output : Two lines.
* Approach: Partition.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(int[] a) {
// Step 1: partitioningBy splits a stream into two lists: the values with a true test and the values with a false test.
java.util.Map<Boolean, java.util.List<Integer>> parts = java.util.Arrays.stream(a).boxed()
.collect(java.util.stream.Collectors.partitioningBy(value -> value % 2 == 0));
// Step 2: Join each list into text. Java % keeps the sign, so -3 % 2 is -1 (not 0), and -3 is correctly odd.
String evens = parts.get(true).stream().map(String::valueOf).collect(java.util.stream.Collectors.joining(" "));
String odds = parts.get(false).stream().map(String::valueOf).collect(java.util.stream.Collectors.joining(" "));
return new String[] {"evens: " + evens, "odds: " + odds};
}
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(String.join("\n", solve(a)));
}
}
Hints (1)
- What is -3 % 2 in Java?