Two Sum

One-pass hash map of value to index — look up the complement before inserting the current value.

Easy
Time O(n) Space O(n)
LeetCode
2 min read
hash-map array

Problem#

Return indices of two numbers in nums that add up to target. Exactly one solution exists; you may not use the same element twice.

Examples#

  • nums=[2,7,11,15], target=9[0,1].
  • nums=[3,2,4], target=6[1,2]; nums=[3,3], target=6[0,1].

Constraints#

  • 2 <= nums.length <= 10^4, -10^9 <= nums[i] <= 10^9.

Approach#

One-pass hash map. For each index i, check whether target - nums[i] was seen previously; if so, return that index and i. Else store nums[i] → i.

Solution#

Two Sum
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) {
auto it = seen.find(target - nums[i]);
if (it != seen.end()) return {it->second, i};
seen[nums[i]] = i;
}
return {};
}
};

Editorial#

Looking up the complement before inserting the current value handles the “use the same element twice” trap — if the array had [3,3] and target 6, the second 3 looks up the first. Linear scan beats sort-and-two-pointer when you need original indices.

Complexity#

  • Time: O(n) average.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.