2Brute2Best
🔥0
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”
  1. 1
    Two Sum
    Basic Anchor·LeetCode #1
    Easy
  2. 2
    Contains Duplicate II
    Basic Reinforcement·LeetCode #219
    Easy
  3. 3
    Max Number of K-Sum Pairs
    Slight Variation·LeetCode #1679
    Medium

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?