The two readings that add up
A reconciliation tool has a sorted column of amounts and a difference to explain. It looks for the two amounts that together account for it.
- The amounts arrive sorted ascending.
- Return the two amounts, smaller first.
- If several pairs work, return the one with the smallest first amount.
- If no pair adds up, return an empty list.
- An amount cannot pair with itself — the two have to be at different positions.
pairSummingTo(amounts: list<int>, target: int) → list<int>
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::vector<int> pairSummingTo(std::vector<int> amounts, int target) {
}
Worked examples
| Call | Result |
|---|---|
pairSummingTo(std::vector<int>{1, 2, 4, 7, 11}, 9) | std::vector<int>{2, 7} |
pairSummingTo(std::vector<int>{1, 2, 3, 4}, 5) | std::vector<int>{1, 4} |
pairSummingTo(std::vector<int>{1, 2, 3}, 100) | std::vector<int>{} |
pairSummingTo(std::vector<int>{}, 3) | std::vector<int>{} |
Hint
Sorted input means you can start at both ends. If the two ends add up to too much, the right end is too big; if too little, the left end is too small.
Reference solution in C++
std::vector<int> pairSummingTo(std::vector<int> amounts, int target) {
int i = 0, j = static_cast<int>(amounts.size()) - 1;
while (i < j) {
int sum = amounts[i] + amounts[j];
if (sum == target) return std::vector<int>{amounts[i], amounts[j]};
if (sum < target) i++;
else j--;
}
return std::vector<int>{};
}