Two sum

Question.

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

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

You can return the answer in any order.

Answer:-

we will use a map for solving this problem.

 vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> umap;
        for(int i=0;i<nums.size();i++){
            if(umap.find(target-nums[i])!=umap.end(){
                int element = umap[target-nums[i]];
                        return {element,i};
            }
               umap[nums[i]]=i;
        }
        return {0};
    }
  1. here, we start with creating an unordered map to store the elements of vector nums which is pre-given to us.

  2. then,we run a for loop which run to iterate the nums vector.

  3. And by using an if statement we check the value (target-nums[i]) (which is the value remaining after subtracting with target)

    is present in the map or not.

  4. if the element is present we go ahead in the condition and store the index of value(target-nums[i])

  5. and return the indexes {element,i}

  6. ;or if the condition is not true the value of nums[i] is stored in map(umap[nums[i]]=i)

  7. and if the element is not found and the for loop exits we just return {0}.

Thankyou guys hope you get the point how to solve the problem.