Complexity and efficiency · 10 / 15 Exercise Hard

Two-number sum

Objective

Create a Python program that finds two different positions of a list whose values add up to a target. With two loops it is O(n²); with a dictionary it is O(n).

Instructions

  • Read a line with integers separated by spaces and then a line with the target.
  • Go through the list with index j. Before storing each value, look in the dictionary seen (value → first index) to see whether you already saw the missing one, target - value.
  • If you saw it at index i, show i j (with i < j) and finish. If there is no pair, show No solution. The pair with the smaller second index j wins.
Input
2 7 11 15
9
Output
0 1

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise