Reputation: 151
I have a function match that takes in a list of numbers and a target number and I want to write a function that finds within the array two numbers that add to that target.
Here is my approach:
>>> def match(values, target=3):
... for i in values:
... for j in values:
... if j != i:
... if i + j == target:
... return print(f'{i} and {j}')
... return print('no matching pair')
Is this solution valiant? Can it be improved?
Upvotes: 0
Views: 915
Reputation: 301
There is room for improvement. Right now, you have a nested loop. Also, you do not return
when you use print
.
As you iterate over values
, you are getting the following:
values = [1, 2, 3]
target = 3
first_value = 1
difference: 3 - 1 = 2
We can see that in order for 1 to add up to 3, a 2 is required. Rather than iterating over the values
, we can simply ask 2 in values
.
def match(values, target):
values = set(values)
for value in values:
summand = target - value
if summand in values:
break
else:
print('No matching pair')
print(f'{value} and {summand}')
Edit: Converted values to a set
since it has handles in
quicker than if it were looking it up in a list
. If you require the indices of these pairs, such as in the LeetCode problem you should not convert it to a set
, since you will lose the order. You should also use enumerate
in the for-loop to get the indices.
Edit: summand == value
edge case
def match(values, target):
for i, value in enumerate(values):
summand = target - value
if summand in values[i + 1:]:
break
else:
print('No matching pair')
return
print(f'{value} and {summand}')
Upvotes: 0
Reputation: 23556
The best approach would result in O(NlogN) solution.
All in all, you have O(NlogN) for the sorting and O(N) for the indexing, bringing the complexity of the whole solution to O(NlogN).
Upvotes: 1