Trying my own brute force solution. Now, there is a problem with my code I don't know what the problem is. I calculated the problem on my paper perfectly and it works great. It should work as expected. But gives unexpected results.
Problem: Missing Number
Code:
public static List<Integer> getMissingNumber (List<Integer> arr, List<Integer> brr){
Integer[] value = new Integer[brr.size()];
value = brr.toArray(value);
for(int i=0; i<arr.size();i++){
for(int j=0; j<brr.size(); j++){
if(arr.get(i)==brr.get(j)){
value[j]=0;
break;
}
}
}
Arrays.sort(value);
List<Integer> exect_value = new ArrayList<Integer>();
for(int i=0;i<value.length;i++) {
if(value[i]!=-1) {
exect_value.add(value[i]);
}
}
return Arrays.asList(value);
}
Problem I'm Facing here:
for(int i=0; i<arr.size();i++){
for(int j=0; j<brr.size(); j++){
if(arr.get(i)==brr.get(j)){
value[j]=0;
break;
}
}
}
When I tested for: Taking 2 different input(Function will pass 2 list):
arr[6] : [7,2,5,3,5,3]
brr[8] : [7,2,5,4,6,3,5,3]
output: [4,6]
you have to print elements that is not founded in list_1
It works perfectly for this test case
But
When I try for: Input:
arr[10] =[11 4 11 7 13 4 12 11 10 14]
brr[15] = [11 4 11 7 3 7 10 13 4 8 12 11 10 14 12]
Output gives: [0, 0, 11, 0, 3, 7, 0, 0, 4, 8, 0, 11, 10, 0, 12]
This but
I'm expecting -> [0, 0, 0, 0, 3, 7, 0, 0, 0, 8, 0, 0, 10, 0, 12]
extra [11,4,11]
comes on this array.
Why I'm so confused, please help me.
When I try for: Input:
arr[10] =[11 4 11 7 13 4 12 11 10 14] brr[15] = [11 4 11 7 3 7 10 13 4 8 12 11 10 14 12]
Output gives:
[0, 0, 11, 0, 3, 7, 0, 0, 4, 8, 0, 11, 10, 0, 12]
This but I'm expecting ->[0, 0, 0, 0, 3, 7, 0, 0, 0, 8, 0, 0, 10, 0, 12]
extra[11,4,11]
comes on this array.
That is because here:
for(int i=0; i<arr.size();i++){ for(int j=0; j<brr.size(); j++){ if(arr.get(i)==brr.get(j)){ value[j]=0; break; } } }
you are comparing arr.get(i)
with brr.get(j)
instead of value[j]
.
PS. I seems that the proper solution is to sort and "anti-merge" two lists:
public static List<Integer> missingNumbers(List<Integer> arr, List<Integer> brr) {
// Write your code here
Collections.sort(arr);
Collections.sort(brr);
Set<Integer> result = new LinkedHashSet<>();
int l = 0, r = 0;
while (l < arr.size() && r < brr.size()) {
if (arr.get(l).equals(brr.get(r))) {
l++;
r++;
} else {
result.add(brr.get(r++));
}
}
for (; r < brr.size(); r++) {
result.add(brr.get(r));
}
return new ArrayList<>(result);
}