Intersection of Two Arrays
Problem
Print the different values that appear in both arrays, in ascending order. Print none if there is no common value.
Constraints
- 1 <= n, m <= 10^5
Examples
Input
4 1 2 2 1 2 2 2
Output
2
Solutions
A set makes the lookup O(1). So the whole task takes O(n + m) instead of O(n * m).
/*
* Problem : Common values.
* Input : Two arrays.
* Output : The sorted common values.
* Approach: Use a set.
* Time : O(n + m + k log k)
* Space : O(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: Put the values of the first array in a set. A set finds a value in constant time.
java.util.Set<Integer> first = new java.util.HashSet<>();
for (int value : a) {
first.add(value);
}
// Step 2: Keep the values of the second array that are in the first set. TreeSet sorts them and removes duplicates.
java.util.TreeSet<Integer> common = new java.util.TreeSet<>();
for (int value : b) {
if (first.contains(value)) {
common.add(value);
}
}
// Step 3: Make the output text.
if (common.isEmpty()) {
return "none";
}
StringBuilder text = new StringBuilder();
for (int value : common) {
text.append(text.length() == 0 ? "" : " ").append(value);
}
return text.toString();
}
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 (1)
- Which data structure finds a value fastest?