Two sums

Written by haloboy777 on 2023-11-18T11:36:12

The classic two sums problem

Problem statement

You are given an array of Integers and another integer targetValue. Write a function that will take these inputs and return the indices of the 2 integers in the array that add up targetValue.

Solution

Brute force

The brute force solution is quite simple. We can use 2 loops to iterate over the array and check if the sum of the 2 numbers is equal to the targetValue. If it is, we can return the indices of the 2 numbers.

Hash table

We can use a hash table to store the numbers and their indices. Then we can iterate over the array and check if the difference between the targetValue and the current number is in the hash table. If it is, we can return the indices of the 2 numbers.

Code

Brute force

vector<int> twoSum(vector<int>& nums, int target) {
    for(int i = 0; i < nums.size(); i++) {
        for(int j = i + 1; j < nums.size(); j++) {
            if(nums[i] + nums[j] == target) {
                return {i, j};
            }
        }
    }
    return {};
}

Hash table

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> hash;
    for(int i = 0; i < nums.size(); i++) {
        if(hash.find(target - nums[i]) != hash.end()) {
            return {hash[target - nums[i]], i};
        }
        hash[nums[i]] = i;
    }
    return {};
}
×