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
The main problem with solutions testing all possible couples (with imbricated loops or itertools.combinations
) is that that are O(n^2), as you basically test all possible combinations of two elements among n (there are n*(n-1)/2 such combinations) until you find a valid one.
When n is large, you will need a more efficient algorithm. One possibility is to first sort the list (this is O(n * log(n))), finding the solution can then be done directly in O(n), which gives you a solution in O(n * log(n)).
We sort the list first, then add the first (smallest) and last (greatest) values. If the sum is too large, we can remove the largest value. If it's too small, we remove the smallest one, until we reach the exact sum.
We can use a collection.deque to efficiently remove values at any end of the list.
In order to retrieve the indices, we keep them besides the values in tuples.
from collections import deque
def find_target(values, target):
dq = deque(sorted([(val, idx) for idx, val in enumerate(values)]))
while True:
if len(dq) < 2:
raise ValueError('No match found')
s = dq[0][0] + dq[-1][0]
if s > target:
dq.pop()
elif s < target:
dq.popleft()
else:
break
return dq[0], dq[-1]
values = [23, 5, 55, 11, 2, 12, 26, 16]
target = 27
sol = find_target(values, target)
print(sol)
# ((11, 3), (16, 7))
# 11 + 16 == 27, indices 3 and 7
print(sol[0][1], sol[1][1])
# 3 7