import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ArrayIntersection {
/**
* Finds the intersection of two integer arrays.
*
* Returns only unique values that exist in both arrays.
*
* Example:
* arr1 = {5, 7, 1, 1, 3, 0, 6, 2}
* arr2 = {2, 8, 8, 6, 9, 3, 3, 4, 4}
*
* Result:
* [2, 3, 6]
*
* Time Complexity:
* O(n + m)
*
* Space Complexity:
* O(n)
*
* where:
* n = arr1.length
* m = arr2.length
*/
public static int[] intersection(int[] arr1, int[] arr2) {
if (arr1 == null || arr2 == null) {
throw new IllegalArgumentException("Input arrays must not be null.");
}
// Stores values from the first array for fast lookups.
Set<Integer> valuesInFirst = new HashSet<>();
for (int value : arr1) {
valuesInFirst.add(value);
}
// Stores unique intersection values.
Set<Integer> result = new HashSet<>();
for (int value : arr2) {
if (valuesInFirst.contains(value)) {
result.add(value);
}
}
// Convert Set<Integer> to int[].
return result.stream()
.mapToInt(Integer::intValue)
.toArray();
}
/**
* Prints an array in a readable format.
*/
private static void printArray(String label, int[] array) {
System.out.println(label + Arrays.toString(array));
}
public static void main(String[] args) {
// Test case from the question.
int[] arr1 = {5, 7, 1, 1, 3, 0, 6, 2};
int[] arr2 = {2, 8, 8, 6, 9, 3, 3, 4, 4};
int[] common = intersection(arr1, arr2);
printArray("Array 1: ", arr1);
printArray("Array 2: ", arr2);
printArray("Intersection: ", common);
System.out.println();
// Additional test cases.
printArray(
"No common values: ",
intersection(
new int[]{1, 2, 3},
new int[]{4, 5, 6}
)
);
printArray(
"Duplicate inputs: ",
intersection(
new int[]{1, 1, 1, 2, 2},
new int[]{1, 1, 2, 2, 3}
)
);
printArray(
"Empty array: ",
intersection(
new int[]{},
new int[]{1, 2, 3}
)
);
}
}
/*
run:
Array 1: [5, 7, 1, 1, 3, 0, 6, 2]
Array 2: [2, 8, 8, 6, 9, 3, 3, 4, 4]
Intersection: [2, 3, 6]
No common values: []
Duplicate inputs: [1, 2]
Empty array: []
*/