The problem: There is a list of positive integers where the elements are unique and monotonically increasing. The list is s. For example s=[1,2,3,4,5,6,7,8,9,10]. The length of the list is n. The goal is to find the total number of ordered pairs (L, W) where L and W are in s that satisfies L*W <= a
The solution of the problem seems straight forward, yet I cannot figure out how did I do it wrong. This was an online assessment problem and I have failed already. If someone can tell me how did I fail, I will be very happy.
The approach is straight forward: for each possible L, find an upper bound of W in s using binary search. My code using Python:
def configurationCount(n, s, a):
# n is the length of s.
num_ways = 0
# Consider every L.
for i in range(n):
L = s[i]
goal = a//L
# Binary search for this upper bound in s.
i = 0
j = len(s) - 1
mid = (i+j)//2
exact_match = False
valid = False
cursor = -1
while(i<=j):
if goal > s[mid]:
i = mid+1
cursor = mid
mid = (i+j)//2
elif goal < s[mid]:
j = mid - 1
cursor = mid
mid = (i+j)//2
else:
exact_match = True
cursor = mid
break
if cursor in range(n) and L*s[cursor]<=a:
valid = True
if cursor in range(n) and valid:
num_ways += (cursor + 1)
return num_ways
This code only gave one correct output for one test case, but failed for the other 10 test cases. In one case where I could see that my out put was wrong, the correct output was more than 2000, where mine was about 1200. So I probably did not count some cases. Yet this approach seems so standard but how did I do it wrong?