Given a random list of numbers, your task is to find the two indices that added together equal the target number.
For example:numbers = [3, 10, 14, 8, 15, 5, 16, 13, 9, 2] target = 30 result = (2, 6)
To make it a bit harder there are some conditions you should meet:
- the number at index 1 < number at index2
- if there are multiple indices leading to the right target number, you must return the one where the number at index 1 is the smallest, so if we need to get to 5224 (used in one of the tests) and we have the following contenders the former wins, because it has the smallest value at the first index:index 31: 476 index 42: 4748 total: 5224 index 21: 1675 index 29: 3549 total: 5224
You can assume that each solution only has one correct answer. If no solution can be found, just return
None. Good luck!
You are free to implement it as you want, but for the fastest solution you might want to follow these steps (again, not required): assuming we have two indices pointing to two of the values in the numbers list,
j. The sum of
jcould only fall into one of these three possibilities:
i + j > target- increasing
iins't going to help us, as it makes the sum even bigger. Therefore we should decrease
i + j < target- decreasing
jisn't going to help us, as it makes the sum even smaller. Therefore we should increase
i + j == target- We have found the answer
This challenge was adapted from Leetcode Clean Code Handbook