Classic algorithms · 16 / 22 Exercise Medium

Pair with a given sum

Objective

Create a Python program that finds two numbers in a sorted list that add up to a given value, using the two-pointer technique.

Instructions

  • Read a line with integers sorted from smallest to largest and, on the next line, the target sum.
  • Use i = 0 (start) and j = len(list) - 1 (end). While i < j: compute s = list[i] + list[j]. If s is the target, finish; if it is smaller, move i forward; if it is larger, move j back.
  • If you find the pair, show Pair: a + b = target with the first one this procedure finds. Otherwise, show No pair.
Input
1 3 4 6 8 11
10
Output
Pair: 4 + 6 = 10

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

Start exercise