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.
arr.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.
Check whether any two numbers in arr add up to target.
[].You can return the two numbers in any order — [3, 4] and [4, 3] are both fine.
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.
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."
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.
A beginner's first idea is usually to try every possible pair:
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.
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.