what is the solution of this by python 3 ?
Given an array of integers, return indices of the two numbers such that they add up to a spe
We can use to pointers, at the beginning and at the end of the list to check each index by the sum of the two numbers, looping once.
def sumOfTwo(array, target):
i = 0
j = len(array) - 1
while i < j:
add = array[i] + array[j]
if add == target:
return True
elif add < target:
i += 1
else:
j -= 1
return False
input -> [1, 2, 3, 4] -> target: 6
i-> <-j
[1][2][3][4] if i + j = target return True
if i + j < target increase i
else decrease j
Note: In a edge case, a guard of check before the loop, in case: target is a negative value, list is empty, target is null.