Working on a problem, have an input array, sorted positive unique integer, try to find all possible triples (x,y,z)
which satisfy x+y>z
and x<y<z
. For example (1,2,3)
is not a valid triple since 1+2
is not > 3
, and (3,4,5)
is a valid triple since 3<4<5
and 3+4>5
.
I post my code which leverage binary search, wondering if any better solutions in terms of time complexity? Please also help to point out any code issues/bugs or improvement areas. Thanks.
Implementation,
# find upper bound of value, including value itself
def findUpperBound(numbers, value, start):
if not numbers:
raise 'value eror'
low = start
high = len(numbers) - 1
while low <= high:
mid = (low + high) // 2
if numbers[mid] == value:
return mid
elif numbers[mid] > value:
high = mid - 1
else:
low = mid + 1
# if reach here, means find an upper bound
return low
if __name__ == "__main__":
result = set()
numbers=[1,2,4,5,6,7,8,10]
for i in range(0, len(numbers)-2):
for j in range(i+1, len(numbers)-1):
k = findUpperBound(numbers, numbers[i] + numbers[j], j+1)
for p in range(j+1, k):
result.add((numbers[i], numbers[j], numbers[p]))
print result
Output,
set([(5, 7, 10), (4, 6, 8), (5, 7, 8), (4, 8, 10), (6, 8, 10), (2, 6, 7), (5, 6, 7), (4, 5, 6), (5, 6, 8), (2, 4, 5), (5, 6, 10), (2, 7, 8), (5, 8, 10), (4, 7, 8), (7, 8, 10), (6, 7, 8), (2, 5, 6), (6, 7, 10), (4, 5, 7), (4, 5, 8), (4, 6, 7), (4, 7, 10)])