2 POINTERS › TWO POINTER ON ARRAYS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →For a value x at index i to belong to the answer, its partner is not arbitrary: it must equal target - x. The problem therefore becomes a search for one earlier value while scanning the array. If that partner has already appeared, its stored index and i form the answer immediately.
Store each value together with its index as you pass it. The order matters: look for target - nums[i] before storing nums[i] itself. That guarantees the stored partner comes from a different index, so the current element can never be matched with itself. The unique-answer guarantee means the first match is enough.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) expected | Each index is processed once, with one expected constant-time lookup and at most one expected constant-time insertion. The scan stops at the match, so it never does more than n iterations; pathological hash collisions can degrade this to O(n^2). |
| Space | O(n) extra | The map stores at most one entry per scanned element, and the returned two-index vector is required output excluded from working-space usage. In the worst shape, the matching pair is at the end, so nearly all n values remain stored. |
#include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); i++) {
int need = target - nums[i];
auto it = seen.find(need);
if (it != seen.end()) {
return {it->second, i};
}
seen[nums[i]] = i;
}
return {};
}
};The two key lines are the lookup and the insertion order. At index i, find the complement among earlier elements first. Only when it is absent do you record the current value. This handles duplicates naturally: for [3, 3] with target 6, the first 3 is stored and the second 3 finds it, producing two different indices.