LeetCode-1 | Two sum | C++

Chandra Kiran
May 25, 2021

--

Two sum - Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

TIP - always think of brute force algorithm first and come up with enhanced code later.

Brute force solution :

It’s done using two nested for loops .

Time complexity — O(n²)

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

return a;
}
};

O(n) solution :

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i,j;
vector<int> a;
unordered_map<int,int> mpp;

for(i=0;i<nums.size();i++){
int rem = target-nums[i];
if(mpp.find(rem) != mpp.end()){
a.push_back(mpp[rem]);
a.push_back(i);
return a;
}
mpp[nums[i]] = i;
}

return a;
}
};

--

--

Chandra Kiran
Chandra Kiran

No responses yet