Working on below problem, looking for advice on code style, functional bug and time complexity improvements.
Also looking for advice in,
- If array is not sorted, any solutions available for O(n^2) time complexity?
- In my loop, I always search from
exclude_index + 1
to reduce duplicate, is it a safe start boundary?
Problem,
Given a sorted array and a target number, tell whether there are three numbers in the array which add up to the target number. (Time complexity should be O(n^2))
Source code,
def two_sum(numbers, start, end, target, exclude_index):
while start < end:
if start == exclude_index:
start += 1
elif end == exclude_index:
end -= 1
elif numbers[start] + numbers[end] > target:
end -= 1
elif numbers[start] + numbers[end] == target:
print numbers[start], numbers[end], numbers[exclude_index]
start += 1
end -= 1
while start < end and (numbers[start] == numbers[start - 1] or start == exclude_index):
start += 1
while start < end and (numbers[end] == numbers[end + 1] or end == exclude_index):
end -= 1
else:
start += 1
def three_sum(numbers, target):
for exclude_index in range(len(numbers)):
if exclude_index > 0 and numbers[exclude_index] == numbers[exclude_index - 1]:
continue
two_sum(numbers, exclude_index + 1, len(numbers) - 1, target - numbers[exclude_index], exclude_index)
if __name__ == "__main__":
numbers = [1, 3, 4, 6, 7, 8, 9, 9, 10, 12]
three_sum(numbers, 15)