I have the quadratic solution for the problem as below:
A = [12, 45, 23, 50, 87, 57]
B = [32, 10, 12, 57, 34, 99]
for i in range(len(A)):
for j in range(len(B)):
if A[i] == B[j]:
print(A[i])
This is of course O(N^2)
.
Another solution I thought about is sorting list B
which is O(n*log(n))
then binary search into B
is O(log(n))
, and then doing that N
times for all items in A
. So that's a worst case complexity of O(2*n*log(n)))
but w can drop the 2
since it's a constant and we have O(n*log(n))
.
Is that correct? Is there a way to improve that even further?