Reputation: 267
Is it possible to find out one missing element from one array that is not present in other array using single for loop in Java
e.g. a1 = {2,5,1,9,3,4} , length n+1
a2 = {2,4,1,5,3} , length n
missing element - 9 Using only a single for loop not by collections. Is it possible??
Upvotes: 2
Views: 1425
Reputation: 7032
At the most basic, if we are always talking about numbers, just sum the suckers.
int sumOne = 0;
int sumTwo = 0;
for(int i = 0; i < a1.length; i++){
sumOne += a1[i];
if(i < a2.length)
sumTwo += a2[i];
}
int missingNumber = sumOne - sumTwo;
If the elements aren't always numbers... Ask for more loops.
Upvotes: 9
Reputation: 2411
Find missing element using XOR
class Main {
public static void main(String[] args) {
int[] a1 = { 2, 5, 1, 9, 3, 4 };
int[] a2 = { 2, 4, 1, 5, 3 };
int missingElement = a1[a1.length - 1];
for (int i = 0; i < a2.length; i++) {
missingElement = missingElement ^ a1[i] ^ a2[i];
}
System.out.println(missingElement);
}
}
Upvotes: 4
Reputation:
sum the 2 arrays in one loop then subtract (max - min) = the missing element
Upvotes: 2