01
Complement lookup (Arrays & Hashing Sub-pattern)
For each element, work out the partner it needs and check whether that partner was already seen. Then record the current element for the ones that come later.
Signals in the problem statement
- ›
"two numbers that add up to target" (unsorted)
- ›
"return the indices"
- ›
"nums[i] == nums[j] and |i − j| ≤ k"
- ›
"pairs that sum to k", each used once
What makes it different
The map's value depends on the question: an index (Two Sum), the latest index (closest duplicate), or a count of unused copies (k-sum pairs).
Questions
ordered from “learn the idea” to “recognise it without help”- 1Two SumWalkthroughEasyBasic Anchor·LeetCode #1
- 2Contains Duplicate IIWalkthroughEasyBasic Reinforcement·LeetCode #219
- 3Max Number of K-Sum PairsWalkthroughMediumSlight Variation·LeetCode #1679
Template
complement-template.cpp
// For each element, ask: "is the partner I need already seen?"
vector<int> findPair(vector<int>& nums, int target) {
unordered_map<int, int> seen; // value -> index where we saw it
for (int i = 0; i < (int)nums.size(); i++) {
int need = target - nums[i];
auto it = seen.find(need); // look up FIRST...
if (it != seen.end()) return {it->second, i};
seen[nums[i]] = i; // ...then remember the current element
}
return {};
}Remember this · Arrays & Hashing
Trigger
"Have I seen X before?", pairs that add up to a target, grouping things that look alike, counting occurrences.
Think
Instead of scanning again for each element, can I remember earlier elements in a map?
Key question
What exactly do I store as the key, and what as the value?