215. Python Program to Find Two Numbers That Add Up to a Target
MediumPhase 2 · Practice
This one takes a few steps. It uses two for loops, one inside the other, and break. You know both.
Overview
This is the famous two-sum question, one of the most asked coding interview questions. Games and money apps use the same idea to find two values that make an exact total.
Problem Statement
Nadia plays a card game. Each card shows a whole number, and a number can be 0 or less than 0. Nadia wins a round with two cards that add up to exactly the target number.
- The two numbers must be at two different positions. A number cannot be used with itself, but two equal numbers at different positions are fine.
- Look for the pair in this order: the first number with every number after it, then the second number with every number after it, and so on. Print the first pair you find.
- Print
Pair: <a> + <b> = <target>, with the two numbers in the order they appear in the list. - If no pair adds up to the target, print
No pair adds up to <target>.
Examples
Example 1. Input:
4 1 5 2
6
gives:
Pair: 4 + 2 = 6
Why: 4 is tried first, with 1, then 5, then 2. 4 + 2 is 6, so this pair is found before 1 + 5.
Example 2. Input:
3 4
6
gives:
No pair adds up to 6
Why: 3 + 3 would be 6, but there is only one 3, and a number cannot be used with itself.
Input
Two lines. Line 1: whole numbers with one space between them (2 numbers or more). The numbers can be negative. Line 2: the whole number target. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: Pair: <a> + <b> = <target> or No pair adds up to <target>. The tests try 8 different inputs, also two equal numbers, 0 and negative numbers.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.