retagged by
409 views
0 votes
0 votes

Consider two arrays A and B which are integer types. Array A has n distinct values in it and array B also has n distinct values in it, but A and B can share some values. What is the worst-case running time to compute A – B?

 

Approach:

Create array H_A.
Scan A and set H_A[A[i]] = 1

Scan B and set H_A[B[i]] = 0, if H_A[B[i]] is 1.
Scan H_A and get A-B.

Time complexity O(n).

However, the given solution is :


Is it always assumed that the algorithm should work without any auxiliary space?

retagged by

1 Answer

2 votes
2 votes

Actually it should be given that we are allowed to use some extra space or in solving the problem.

In this question your approach is correct as we can find the intersection in O(n+n)=O(2n)=O(n) time .

and then remove them using hash function ,

And in fact in cpp there is an inbuild set difference operation we have works in linear time depending on range of number.

http://www.cplusplus.com/reference/algorithm/set_difference/

So given space we can do it less time and it is always a trade off between time and space.

Related questions

0 votes
0 votes
1 answer
1
1 votes
1 votes
0 answers
3
Raviwarlord asked Jan 4, 2023
447 views
can anyone verify if options are correct i am not satisfied with the solution given.
1 votes
1 votes
1 answer
4
Raviwarlord asked Jan 4, 2023
306 views
Could anyone give an example why 2nd and 3rd were false.