Finding intersection of two arrays can be done if you sort the 2 arrays and then do a linear step through to record the common elements.
This would take O(nlogn) + O(nlogn) + O(n)
Alternatively, you could compare each element in the first array with each element in the second array and you would get a O(n^2) run-time complexity.
How can I prove the first approach is better than the second?
First of all,
O(nlogn) + O(nlogn) + O(n)doesn’t make much sense, sinceO(f)is a set, not a number.What you mean is
O(nlogn + nlogn + n), which can be shown to be equal toO(nlogn). Just look at what it means for a functionfto belong to the setO(g):fis an element ofO(g)iff there existsc>0andx0such that for allx>x0:|f(x)| <= c*|g(x)|By setting
f=nlognandg=nlogn+nlogn+n, it follows thatfis inO(g), and hence thatO(nlogn) == O(nlogn + nlogn + n).