Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to find the intersection of two arrays (values that exist in both arrays) in Java

1 Answer

0 votes
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: []

*/

 



answered Sep 28 by avibootz
...