Solution: Find Two Numbers That Add Up to "n"
This review provides a detailed analysis of the different ways to solve the previous challenge.
We'll cover the following...
Solution #1: brute force
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 elements, the time complexity is .
Solution #2: sorting the list
Explanation
While solution #1 is very intuitive, it is not very time efficient. A better way to solve this is by first sorting the list. Then, for each element in the list, use a binary search to look for the difference between that element and the intended sum. You can implement the binary_search function however you like, recursively or iteratively. So, if the intended sum is n and the first element of the sorted list is a0, then you will conduct a binary search for n-a0 and so on for every a ...