I have a question being asked in interview.
There are 2 arrays.
arr1 = {3,5,6,8,1,6,7};
arr2 = {5,6,8};
so the final output is
arr1 = {3,8,1,7};
I could answer it with O(n^2) time.
Is there a better way of doing it.
Regards,
Rajesh
I have a question being asked in interview.
There are 2 arrays.
arr1 = {3,5,6,8,1,6,7};
arr2 = {5,6,8};
so the final output is
arr1 = {3,8,1,7};
I could answer it with O(n^2) time.
Is there a better way of doing it.
Regards,
Rajesh
You can do it in O(n) by using a HashSet. Add second array elements in a HashSet and iterate first array in one pass -
This will give you O(n)
Implementation in Java below. Please ignore any typos
int[] arr2 = {5,6,8};
Set toBeRemoved = new HashSet<Integer>();
for(int i:arr2){
toBeRemoved.add(i);
}
for(int i:arr1){
if(toBeRemoved.contains(i)){
//Logic to remove from array
//Or else if you dont have space contraint just add elements to a new array
}
}