Code Blog Wasif Islam

Two Sum

Two Sum – (Easy)

Description:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Naive Solution:

For each element, iterate through remaining elements and check for compliment.

Solution:

Make a HashSet/unordered_set. Iterate throuhg each element and check if the hashset contains the compliment. If not, store the <element, index> as key and value. (store the value of the element, as it will be the compliment of the other correct element)

My Naive Code:

C++ ~O(n2)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
            int compliment = target - nums[i];
            for (int j = i + 1; j < nums.size(); j++) {
                if (nums[j] ==  compliment) {
                    vector<int> solution = {i, j};
                    return solution;
                }
            }
        }
    }
};

My Code:

C++ ~O(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> compliments; // <comliment, index>
        for (int i = 0; i < nums.size(); i++) {
            int compliment = target - nums[i];
            if (compliments.count(compliment)) {
                vector<int> solution = {compliments.at(compliment), i};
                return solution;
            }
            compliments.insert(make_pair(nums[i], i));
        }
        vector<int> fail = {-1, -1};
        return fail;
    }
};