C++20 sections · 1024 units
Open in Course

Two Sum Problem

Classic problem

Given an array and target sum, find two elements that add up to the target. For each element x, check if target - x exists in a map of previously seen values. Build the map as you scan: if (seen.count(target - x)) you found a pair; otherwise add seen[x] = i to record this element.

This finds pairs in O(n)O(n) time. Without a map, you'd need O(n2)O(n^2) nested loops or O(nlogn)O(n \log n) with sorting and two pointers. Maps make this classic interview problem simple to solve.