I'm trying to find an efficient way in Java to check whether two arrays have at least one element in common element-wise. So this means [1, 2, 2, 3] and [2, 3 ,5 ,6] would give False, whereas [1, 2, 2, 3] compared with [5, 2, 1, 5] would give True. Currently I loop over the elements, and break out of the loop once one of the elements is equal. Is there a more efficient way?
Asked
Active
Viewed 599 times
0
-
1`[1, 2, 2, 3]` and `[2, 3 ,5 ,6]` do have an element in common though? – achAmháin Jan 26 '18 at 11:46
-
Also, if you have working code, better to post it on https://codereview.stackexchange.com/ – achAmháin Jan 26 '18 at 11:46
-
4I don't think it is possible in a more efficient way! – Wasi Ahmad Jan 26 '18 at 11:50
-
@notyou: no, this is what i meant with element-wise. In order for the test to return true, the equal element should be at the same position in the array. And to David, I believe the same response holds as well for the link you gave me. They look for common elements of two sets, not element-wise comparison. Thanks guys! – blah_crusader Jan 26 '18 at 11:53
-
@user3343378 I'd edit your question to specify that, as that was not mentioned. Also, I'd still probably go to the code review site if you have working code. In your scenario, breaking out of the loop once found is probably your best option. – achAmháin Jan 26 '18 at 11:54
-
@notyou: I believe my title & tag state clearly it is an element-wise check? Thanks for the tips. – blah_crusader Jan 26 '18 at 11:58
2 Answers
1
Dont think that you can do better than O( min(array1.length, array2.length) )
There are micro optimizations you can do such as loop unrolling ( https://en.wikipedia.org/wiki/Loop_unrolling ) although you may want to think carefully before going down this path.

David Soroko
- 8,521
- 2
- 39
- 51
0
You can compare element by element two arrays and return when you find a match with true, else return false.
public class ArrayCheck {
public static void main(String[] arg){
int[] a = {1, 2, 2, 3};
int[] b = {2, 3 ,5 ,6};
int[] c = {5, 2, 1, 5};
System.out.println("Result " + elementWiseCompare(a,b));
System.out.println("Result " + elementWiseCompare(a,c));
}
public static boolean elementWiseCompare(int[] a, int [] b){
for(int i = 0; i < a.length && i < b.length; i++){
if (a[i] == b[i]){
return true;
}
}
return false;
}
}
Outputs:
Result false Result true

Anurag Sharma
- 2,409
- 2
- 16
- 34
-
Hi Anurag, thanks for this. This is similar to what I'm currently doing. I was hoping there might exist a more efficient way, but I guess it's not really possible :) – blah_crusader Jan 26 '18 at 12:15
-
@user3343378 Thats awesome, this is for generic case unless there is some pattern in the two arrays, we can not get better than O(n) – Anurag Sharma Jan 26 '18 at 12:20