Devise an algorithm that will operate on a number x and a set of n distinct numbers such that in \$O(n \lg n)\$ time, the algorithm indicates whether or not there are two numbers in the set that have a product of x. Explain why your algorithm works.
My algorithm:
- Sort the set //\$ O(n \lg n)\$
- For every element in the set check if x % element =0 // \$O(n)\$
- If so check if the dividend x/element exists in the set // \$O(\lg n)\$
- If dividend exists and is not equal to element, the two numbers in the set (element and dividend) have a product of x.
This algorithm works because it only returns true when the condition(x=element*dividend where element and dividend are in the set) to be satisfied is met. And upon quick Analysis we can see that the algorithm is running at \$O(n\lg n)\$ for the sort and \$O(n)*(\lg n)\$ for checking if the two elements exists. Therefore it is running at \$O(n \lg n) + O(n \lg n) = O(2n \lg n) = O(n \lg n)\$
Can I have some feedback on my solution — whether you think it is correct or not and where you think it can be improved?
def findIfProdExists(x,items):
items = mergeSort(items) # O(nlgn)
for item in items:
if(item!=0):
if x%item ==0:
if item!=x/item and find(x/item,items): #binary Search O(lgn)
return True
return False
def mergeSort(aList):
size = len(aList)
first = aList[:int(size/2)]
second = aList[int(size/2):]
if(size ==1):
return aList
if(size ==2):
if(aList[1]<aList[0]):
return list([aList[1],aList[0]])
else:
return aList
else:
return merge(mergeSort(first),mergeSort(second))
def merge(list1,list2):
newList =[]
i1 =0
i2 =0
while i1<len(list1) and i2 <len(list2) :
if list1[i1] <list2[i2] :
newList.append(list1[i1])
i1+=1
elif list1[i1]>list2[i2] :
newList.append(list2[i2])
i2+=1
else:
newList.append(list1[i1])
i1+=1
newList.extend(list1[i1:] +list2[i2:])
return newList
def find(x,items):
lo = 0
hi = len(items)
while lo<hi:
mid = (lo + hi) // 2
if x == items[mid]:
return True
elif x < items[mid]:
hi = mid
else:
lo = mid + 1
return False
NameError: name 'mergeSort' is not defined
. \$\endgroup\$NameError: name 'find' is not defined
. \$\endgroup\$