...

/

Solution: Find Two Numbers That Add Up to "n"

Solution: Find Two Numbers That Add Up to "n"

This review provides a detailed analysis of the different ways to solve the previous challenge.

Solution #1: brute force

def find_sum(lst, n):
"""
Function to find two number that add up to n
:param lst: A list of integers
:param n: The integer number n
"""
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i] + lst[j] == n and i != j:
return [lst[i], lst[j]]
# Driver code to test above
if __name__ == '__main__':
print(find_sum([1, 2, 3, 4], 5))

Explanation

This is the most time-intensive, but intuitive solution. Traverse the whole list and for each element in the list, check if any two elements add up to the given number n. So, use a nested for loop and iterate over the entire list for each element.

Time complexity

Since we iterate over the entire list of nn elements, the time complexity is O(n2)O(n^2) ...

Access this course and 1400+ top-rated courses and projects.