0

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

3
  • You put the to-be-removed elements in a hash set O(m) amortized, then to check whether an element from the original array should be removed or not, you check for containment in the set. O(n). So, in total, O(m+n). (All this assumes a decently working hash function.) Commented Jan 21, 2017 at 10:29
  • Sorting both would be a good idea. Commented Jan 21, 2017 at 10:29
  • 4
    Please explain the final output. How is 8 present in the final output? Commented Jan 21, 2017 at 10:29

2 Answers 2

1

You can do it in O(n+m) time by constructing a HashSet from the second array to use as a lookup. These lookups run in O(1) and it takes O(m) to build the set.

Then you just iterate over your first array in O(n) and keep only the desired elements.

Sign up to request clarification or add additional context in comments.

Comments

0

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
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.