← All Lessons Lesson 27 / 68
Lesson 27

Two Sum: Finding a Pair That Adds Up to a Target

The Two Sum Problem

Imagine you have a list of numbers, and someone hands you one special number called the target. Your job is to look through the list and find two numbers that add up exactly to that target. If you find such a pair, you hand it back. If no such pair exists, you hand back nothing (an empty list).

This is one of the most famous beginner problems in programming, and it teaches a very useful way of thinking.

What we are given

  • An array (a list) of whole numbers, called arr.
  • A single whole number called target.

A quick reminder: an array is just an ordered collection of values, like boxes lined up in a row. Each box holds one number.

What we must do

Check whether any two numbers in arr add up to target.

  • If a pair exists, return those two numbers inside an array.
  • If no pair works, return an empty array [].

You can return the two numbers in any order[3, 4] and [4, 3] are both fine.

Example 1

Input:  arr = [2, 8, 3, 6, 4], target = 7
Output: [3, 4]

Why? Look at the numbers 3 and 4. They sit inside the list, and 3 + 4 = 7, which is exactly our target. So we return them.

You might wonder: do any other pairs work? 2 + 8 = 10, 2 + 3 = 5, and so on — none of those equal 7 except 3 + 4. So [3, 4] is our answer.

Example 2

Input:  arr = [2, -1, 5, -4, 3], target = 34
Output: []

Here the numbers are small, but the target is 34, which is large. No two numbers in this list can add up to 34. When that happens, we simply return an empty array [] to say "no pair found."

One helpful guarantee

The problem promises something useful: there is never more than one answer. This means you don't have to worry about choosing between many possible pairs. Either there is exactly one correct pair, or there is none at all. This keeps the logic simple.

The simplest way to think about it

A beginner's first idea is usually to try every possible pair:

  1. Take the first number, and add it to each of the other numbers.
  2. Take the second number, and add it to each number after it.
  3. Keep going until you either find a pair that equals target, or run out of pairs.

This "check every pair" approach always works. Later you will learn faster methods, but understanding this brute-force idea first builds the right foundation.

The function we will write

In C++, the starting point looks like this:

class Solution {
public:
    vector<int> twoSum(vector<int> &arr, int target) {

    }
};

The function twoSum receives the list arr and the number target, and it must return a vector<int> (a list of integers) — either the matching pair or an empty list.

Two Sum: Finding a Pair That Adds Up to a Target
Diagram — click to zoom (scroll / drag to pan)