Please tell me the approach of the ques
Please tell me how to solve ir
there are multiple ways to solve this
one of them is
- sort both arrays
- use two pointers(variables) i and j
if(arr1[i]==arr2[j]){
ans.push_back(arr1[i]);
i++;
j++;
}
else if(arr1[i]<arr2[j])
i++;
else
j++;
Reference Code
using hashmaps the above mentioned method i know
???
what you are asking??
The question was mentioned in hashmaps how to solve it using hashmaps
okay i got your point
Approach
- Initialize an empty hash map hs.
- Iterate through the first array and put every element of the first array in the map hs.
- For every element x of the second array, do the following :
Search x in the map hs. If x is present, then print it.
any doubt in this??
or just share the code
It is showing error please check the code
But it was not passing test cases
okay then told me that
for(int i=0;i<arr2.size();i++){
if(hs.find(arr2[i])!=hs.end()){
ans.push_back(arr2[i]);
hs[arr1[i]]--;
}
}
here if condition is not correct
because
suppose 1 is present only once in arr1 but 2 times in arr2
then it will not give correct output
Consider this input
7
1 2 3 1 2 4 4
2 1 3 1 1 1 5
Your Output
[1,1,1,1,2,3]
Correct Output
[1, 1, 2, 3]
How to correct it now?PLease help
- do it like this
for(int i=0;i<arr2.size();i++){
if(hs[arr2[i]]){
ans.push_back(arr2[i]);
hs[arr2[i]]--;
}
}
- there must be a space b/w comma and element of array
Modified Code
I have understood everything thanks now
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.