We use Python 3.6

go back Level: Advanced (img: AV / score: 4) level Bite 134. Two Sums

7 out of 7 users completed this Bite ...
Will you be Pythonista #8 to crack this Bite?

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:

  1. the number at index 1 < number at index2
  2. 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, i and j. The sum of i and j could only fall into one of these three possibilities:

  1. i + j > target - increasing i ins't going to help us, as it makes the sum even bigger. Therefore we should decrease j
  2. i + j < target - decreasing j isn't going to help us, as it makes the sum even smaller. Therefore we should increase i
  3. i + j == target - We have found the answer


This challenge was adapted from Leetcode Clean Code Handbook

Round of applause for @clamytoe for delivering this Bite.

Github login button