Zip and Add Two Lists
Problem
Two arrays are given. Pair the numbers by position (the first with the first, the second with the second) and print the sum of each pair. If the arrays have different lengths, stop at the shorter one. The sums can be bigger than 32 bits.
Constraints
- 1 <= n, m <= 10^5
Examples
Input
3 1 2 3 3 10 20 30
Output
11 22 33
Solutions
The task is a map over pairs. A stream over positions (or zip in Python) says what to do with each pair and leaves the looping to the library.
/*
* Problem : Zip and add.
* Input : n, a, m, b.
* Output : Pair sums.
* Approach: Map over pairs.
* Time : O(min(n, m))
* Space : O(min(n, m))
* 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, int[] b) {
// Step 1: A stream of the positions 0 .. shorter length - 1. Each position becomes the sum of the two numbers.
int length = Math.min(a.length, b.length);
return java.util.stream.IntStream.range(0, length)
.mapToObj(i -> String.valueOf((long) a[i] + b[i]))
.collect(java.util.stream.Collectors.joining(" "));
}
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();
}
int sizeB = scanner.nextInt();
int[] b = new int[sizeB];
for (int i = 0; i < sizeB; i++) {
b[i] = scanner.nextInt();
}
System.out.println(solve(a, b));
}
}
Hints (2)
- What happens when one list is longer?
- Why do we cast to long in Java?