Common Elements between Two Arrays

Find Common Elements between two input Arrays

Example –
Array1 -> {1,2,4,7}
Array2 -> {1,5,7,9,2,8}
=> Common Elements -> {1,2,7}

We will use two ways to solve this.

1.  Use the inbuilt retailAll API of List to keep only common elements in the List

2. Nested loops to check if the element in the first array is present in second array.

package com.java.programs;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class CommonElements {

    public static void commonElements(Integer array1[], Integer array2[]) {
        Set < Integer > numbers1 = new TreeSet < > (Arrays.asList(array1));
        List < Integer > numbers2 = Arrays.asList(array2);

        numbers1.retainAll(numbers2);

        System.out.println(numbers1);
    }

    public static void commonElementsWithOutAPI(Integer array1[], Integer array2[]) {

        Set < Integer > commonNumbers = new TreeSet < > ();

        for (int i = 0; i < array1.length; i++) {
            for (int j = 0; j < array2.length; j++) {
                if (array1[i] == array2[j]) {
                    commonNumbers.add(array1[i]);
                    break;
                }
            }
        }

        System.out.println(commonNumbers);
    }

    public static void main(String[] args) {

        Integer array1[] = {1,2,4,7};
        Integer array2[] = {1,5,7,9,2,8};

        commonElements(array1, array2);
        commonElementsWithOutAPI(array1, array2);


    }

}
[1, 2, 7]
[1, 2, 7]

One comment

  1. The program time complexity can be improved by use of extra memory as Map/Set

    All the elements of any of the two arrays can be put into a map/set in one pass – O(n)

    and while iterating through the 2nd array , each element can be checked in map/set if it is present.
    If preset add the element to the output data structure. ( in O(n) time complexity)

    and hence improving complexity from O(n^2) -> O(n)+ O(n)=O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *