codekofi
← All questions

Two Sum

HardArrays & Hashing

The problem

Given an integer array and a target, return the indices of the two elements that add up to the target.

Exactly one such pair exists, and you may not use the same element twice. Return an empty array if there is no pair.

twoSum({2, 7, 11, 15}, 9)

One of these three is correct

Two lines apart, at the closest.

The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.

1vector<int> twoSum(const vector<int>& nums, int target) {
2
3 int n = nums.size();
4 unordered_map<int, int> seen;
5
6 for (int i = 0; i < n; i++) {
7
8 int need = target - nums[i];
9
10 if (seen.count(need)) {
11 return {seen[need], i};
12 }
13
14 seen[nums[i]] = i;
15 }
16
17 return {};
18}
1vector<int> twoSum(const vector<int>& nums, int target) {
2
3 int n = nums.size();
4 unordered_map<int, int> seen;
5
6 for (int i = 1; i < n; i++) {
7
8 int need = target - nums[i - 1];
9
10 if (seen.count(need)) {
11 return {seen[need], i};
12 }
13
14 seen[nums[i]] = i;
15 }
16
17 return {};
18}
1vector<int> twoSum(const vector<int>& nums, int target) {
2
3 int n = nums.size();
4 unordered_map<int, int> seen;
5
6 for (int i = 1; i < n; i++) {
7
8 int need = target - nums[i];
9
10 if (!(seen.count(need))) {
11 return {seen[need], i};
12 }
13
14 seen[nums[i - 1]] = i;
15 }
16
17 return {};
18}