2 Sum in O(n)

class Solution {
public:
vector twoSum(vector& nums, int target) {

    vector<int>ans;

// put the element into the hashtable with thier index if target- nums[i] is not present inside it
unordered_map<int,int>mp;
for( int i=0;i<nums.size();i++){

// check if target-nums[i] is present in the hashtable or not
if(mp.find(target-nums[i]) != mp.end()){
// if it is present take the index of it and put it into vector
ans.push_back(mp[target-nums[i]]);
// also put the current pointing element index into vector
ans.push_back(i);
return ans;
}

// if target-num[i] is not present into the hashtable then put it
mp[nums[i]] = i;

    }
           return ans;
}

};

Comments (0)