Two Sum
Problem
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Examples
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Constraints
2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109- Only one valid answer exists.
Solution
The target is the result of a lhs + rhs. As we linearly traverse the input, we keep track of the seen values (as lhs). For each new value seen, treat as the rhs and check if we’ve previously seen a target-rhs = lhs which will result in our pair summing to the target.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// Track the LHS
std::unordered_map<int, int> map;
map.reserve(nums.size());
for (size_t i = 0; i < nums.size(); ++i) {
const auto &rhs = nums[i];
const auto lhs = target - rhs;
if (map.contains(lhs)) {
return {map[lhs], static_cast<int>(i)};
}
map[rhs] = static_cast<int>(i);
}
assert(false);
}
};