avatar Bite 134. Two Sums

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

Login and get coding
go back Advanced level
Bitecoin 4X

113 out of 113 users completed this Bite.
Will you be the 114th person to crack this Bite?
Resolution time: ~39 min. (avg. submissions of 5-240 min.)
Our community rates this Bite 4.8 on a 1-10 difficulty scale.
» Up for a challenge? 💪

Focus on this Bite hiding sidebars, turn on Focus Mode.

Ask for Help