retagged by
617 views
1 votes
1 votes

Given two sorted arrays A and B containing distinct elements Array length given as m and n , What is the time complexity to  find the Intersection

My query is since the length of array is given and both array contain distinct elements ( their can be common elements bw A and B). So it should be O(m) if m<n else O(n) instead of O(m+n).

retagged by

1 Answer

2 votes
2 votes
To get an intuitive understanding,

Consider the inputs as:
A: 1, 3, 5, 7, 9
B: 2, 4, 6, 8, 10

Now to find the intersection, you will compare the first elements of each,
On finding that they don't match, you discard the smaller one i.e '1'
Now you have the lists as:
A: 3, 5, 7, 9
B: 2, 4, 6, 8, 10

Now you compare '3' and '2' and end up discarding '2' hence having the lists as:
A: 3, 5, 7, 9
B: 4, 6, 8, 10
.
.
 and so on...

 

So here if you see, you made m+n comparisons.

But if we had lists something like this:
A: 1,2,3,4,5
B: 1,2,3,4,5,6,7.......1000

In the first 5 comparisons itself, you will empty the list A and B and won't have any other elements to compare with elements of B and hence will simply discard them because intersection wont be possible when the other set(here, list) is empty.
So the best case would be O(m) if m is less or O(n) if n is less.

 

So worst case: O(m+n)
Best case: O(m) or O(n) whichever is less.
edited by

Related questions

1 votes
1 votes
0 answers
1
0 votes
0 votes
1 answer
2
0 votes
0 votes
3 answers
3
3 votes
3 votes
1 answer
4
Sanjay Sharma asked Feb 20, 2018
1,106 views
An array A is of length n has log( n) distinct numbers.What is the time complexity of sorting A by best comparison based algorithm ?