DSA · Beginner · Pattern 1 of 11
Arrays & Hashing
15 problems.
Your progress0%
- 1st Visit
- 0/15
- 2nd Visit
- 0/15
- Revise
- 0/15
About this pattern
Arrays store elements contiguously, giving O(1) access by index; hash maps and hash sets add O(1) average-time lookup by value. Together they turn many brute-force O(n^2) pair searches into a single O(n) pass: as you scan, record what you have seen and ask whether the complement, duplicate or group key already exists.
Reach for this pattern when a statement asks whether a value has appeared before, to count frequencies, to group items that share a property, or to find a pair with a given sum or difference. Typical cost is O(n) time and O(n) extra space; sorting is the O(n log n) alternative when memory is tight.
// Scan once; the map remembers everything seen so far.
unordered_map<long long, int> seen; // key -> count (or index)
long long answer = 0;
for (int i = 0; i < n; ++i) {
long long want = complementOf(a[i]); // e.g. target - a[i]
auto it = seen.find(want);
if (it != seen.end()) answer += it->second;
seen[keyOf(a[i])]++;
}