In this post of How find common elements between two Arrays. we will understand how to find common elements between two given Arrays.It is a very common interview question where it is asked with a condition not to use any inbuilt classes or methods or any inbuilt data structure like List or Set.
A very simple solution to find common elements between two given arrays is to loop through one of the array in the outer loop and then traverse through the other array in the inner loop and compare the element of the outer array element with all the elements of the inner array.
If same element is found print it and break from the inner loop.
You may also like –
Find largest and smallest number in the given Array
Find duplicate elements in an Array
Java program with array of Integers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kkjavatutorials.client; public class FindCommonElementsFromArrays1 { public static void main(String[] args) { int[] inputArray1 = { 20, 30, 32,100,199,201,500 }; int[] inputArray2 = {600,500,30,201,299,900,901 }; //Loop through the first input array(inputArray1) in the outer loop for (int i = 0; i < inputArray1.length; i++) { /*traversing through the second input array(inputArray2) in an inner loop and compare the element of the outer array(inputArray1) with all the elements of the inner array*/ for (int j = 0; j < inputArray2.length; j++) { if (inputArray1[i] == inputArray2[j]) { System.out.println(inputArray1[i]); break; } } } } } |
Output:
1 2 3 |
30 201 500 |
Java program with array of Strings
Here is the logic to find common elements between two arrays remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kkjavatutorials.client; public class FindCommonElementsFromArrays2 { public static void main(String[] args) { String[] inputArray1 = { "Mumbai", "Chennai","New York", "California" }; String[] inputArray2 = { "California", "Mumbai", "Alaska", "Arizona", "Delaware", "New York" }; //Loop through the first input array(inputArray1) in the outer loop for (int i = 0; i < inputArray1.length; i++) { /*traversing through the second input array(inputArray2) in an inner loop and compare the element of the outer array(inputArray1) with all the elements of the inner array*/ for (int j = 0; j < inputArray2.length; j++) { if (inputArray1[i].equals(inputArray2[j])) { System.out.println(inputArray1[i]); break; } } } } } |
Output:
1 2 3 |
Mumbai New York California |
That’s all about this topic Java Program to find duplicate elements in an Array. If you have any doubts or any suggestions to make please drop a comment.