0
0
JavaProgramBeginner · 2 min read

Java Program to Find Common Elements in Two Arrays

You can find common elements in two arrays in Java by using a HashSet to store elements of one array and then checking which elements of the second array are contained in that set, like this: Set set = new HashSet<>(); for (int num : array1) { set.add(num); } for (int num : array2) { if (set.contains(num)) { /* common element */ } }.
📋

Examples

Inputarray1 = {1, 2, 3}, array2 = {2, 3, 4}
OutputCommon elements: 2 3
Inputarray1 = {5, 6, 7}, array2 = {8, 9, 10}
OutputCommon elements:
Inputarray1 = {}, array2 = {1, 2}
OutputCommon elements:
🧠

How to Think About It

To find common elements, first think of one array as a collection you can quickly check membership in. Put all elements of the first array into a set, which lets you check if an element exists in constant time. Then, go through the second array and check if each element is in the set. If yes, that element is common to both arrays.
📐

Algorithm

1
Create an empty set to store elements of the first array.
2
Add all elements of the first array into the set.
3
Create a list or set to store common elements.
4
For each element in the second array, check if it exists in the set.
5
If it exists, add it to the common elements collection.
6
Print or return the common elements.
💻

Code

java
import java.util.*;

public class CommonElements {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
        int[] array2 = {3, 4, 5, 6, 7};

        Set<Integer> set = new HashSet<>();
        for (int num : array1) {
            set.add(num);
        }

        System.out.print("Common elements: ");
        for (int num : array2) {
            if (set.contains(num)) {
                System.out.print(num + " ");
            }
        }
    }
}
Output
Common elements: 3 4 5
🔍

Dry Run

Let's trace the example arrays {1, 2, 3, 4, 5} and {3, 4, 5, 6, 7} through the code.

1

Add elements of first array to set

Set after adding: {1, 2, 3, 4, 5}

2

Check elements of second array against set

Check 3 (in set), 4 (in set), 5 (in set), 6 (not in set), 7 (not in set)

3

Print common elements

Output: 3 4 5

Element in array2Is in set?Action
3YesPrint 3
4YesPrint 4
5YesPrint 5
6NoSkip
7NoSkip
💡

Why This Works

Step 1: Use a set for fast lookup

A HashSet stores elements so you can check if an item exists quickly, unlike searching an array which takes longer.

Step 2: Add first array elements to the set

Putting all elements of the first array into the set prepares for quick membership checks.

Step 3: Check second array elements against the set

For each element in the second array, checking if it is in the set tells us if it is common.

🔄

Alternative Approaches

Using nested loops
java
public class CommonElementsNested {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3};
        int[] array2 = {2, 3, 4};
        System.out.print("Common elements: ");
        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                if (array1[i] == array2[j]) {
                    System.out.print(array1[i] + " ");
                    break;
                }
            }
        }
    }
}
Simple but slower because it checks every pair, making it O(n*m) time.
Using sorting and two pointers
java
import java.util.Arrays;

public class CommonElementsSorted {
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4};
        int[] array2 = {3, 4, 5, 6};
        Arrays.sort(array1);
        Arrays.sort(array2);
        int i = 0, j = 0;
        System.out.print("Common elements: ");
        while (i < array1.length && j < array2.length) {
            if (array1[i] == array2[j]) {
                System.out.print(array1[i] + " ");
                i++;
                j++;
            } else if (array1[i] < array2[j]) {
                i++;
            } else {
                j++;
            }
        }
    }
}
Efficient for sorted arrays, O(n log n + m log m) due to sorting, then O(n + m) to find common elements.

Complexity: O(n + m) time, O(n) space

Time Complexity

Adding all elements of the first array to a HashSet takes O(n). Checking each element of the second array against the set takes O(m). Total is O(n + m).

Space Complexity

The HashSet stores up to n elements from the first array, so space is O(n).

Which Approach is Fastest?

Using a HashSet is generally fastest for unsorted arrays. Nested loops are slow (O(n*m)). Sorting and two pointers is good if arrays are already sorted or sorting is acceptable.

ApproachTimeSpaceBest For
HashSetO(n + m)O(n)Unsorted arrays, fast lookup
Nested loopsO(n * m)O(1)Very small arrays or no extra space
Sorting + Two pointersO(n log n + m log m)O(1)Sorted arrays or when sorting is allowed
💡
Use a HashSet to check membership quickly instead of nested loops.
⚠️
Trying to compare every element with nested loops without using a set or sorting, which is slow for large arrays.