Challenge: Two Sum
Completed
Read n numbers and a target. Print the indexes of the two numbers that add up to the target, smaller index first. There is exactly one answer. Aim for O(n) with unordered_map.
Input
Line 1: n target. Line 2: n whole numbers.
Output
i j
Example
Input
4 9 2 7 11 15
Output
0 1
Editor
C++
Hints
The partner of x is target - x.
Check the map before adding the current number.
Solution explanation
Keep reading after the answer so every input number is consumed; each lookup is O(1).
Show solution
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
int n, target;
cin >> n >> target;
unordered_map<int, int> seen;
bool done = false;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
if (!done && seen.count(target - x)) {
cout << seen[target - x] << " " << i << endl;
done = true;
}
seen[x] = i;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module