# finding common elements in two integer arrays java

## finding common elements in two integer arrays java

an alternative solution for `findCommonElement method`

``````public int[] findCommonElement(int[] a, int[] b){
Set<Integer> set = new HashSet<Integer>();
for(int ele:a){
}

for(int ele:b){
if(set.contains(ele)){
}
}

int[] arr = new int[array.size()];
for(int i = 0; i < array.size();i++){
arr[i] = array.get(i);
}
return arr;
}
``````

here is an O(m+n) solution:

``````static ArrayList<Integer> commonElements(int[] array1, int[] array2) {
int p1 = 0;
int p2 = 0;
ArrayList<Integer> common = new ArrayList<Integer>();

while(true) {
if (array1[p1] == array2[p2]) {
}
if (p1 == array1.length - 1 || p2 == array2.length - 1) break;
if (array1[p1 + 1] < array2[p2 + 1]) {
p1++;
} else {
p2++;
}
}
return common;
}
``````

#### finding common elements in two integer arrays java

Basically the number of common element from the two elements will be dynamic. Hence if you try to put common elements into an array then it wont be possible as you need to declare size of this array (which in this case will be dynamic).

Consider using list. Ive tried to keep the logic as simple as possible along with comprehensive variable names.

``````    import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test {

public static void main(String[] args) {

int myArray[] = { 2, 2, 7, 7, 2, 1, 5, 4, 5, 1, 1 };
int myArray2[] = { 2, 3, 4, 7, 10 };

Test hello = new Test();
System.out.println(hello.findCommonElement(myArray, myArray2));
}
/**
*
* @param a
* @param b
* @return commonElements
*/
public List<Integer> findCommonElement(int[] a, int[] b) {

List<Integer> commonElements = new ArrayList<Integer>();

for(int i = 0; i < a.length ;i++) {
for(int j = 0; j< b.length ; j++) {
if(a[i] == b[j]) {
//Check if the list already contains the common element
if(!commonElements.contains(a[i])) {
//add the common element into the list