Two Sum | Problem No. 1 | LeetCode

Subscribe to my newsletter and never miss my upcoming articles

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.

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2:

Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3:

Input: nums = [3,3], target = 6 Output: [0,1]

Constraints:

2 <= nums.length <= 103 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists.

Solution:

  1. Add the elements in array to map along with their indices.
  2. Then check the value = target - nums[i] in the map
  3. If present, then check that element is not the same element in the array ( i.e., map[value] is not same as nums[i]).
  4. If present, return that value.
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int> m;
        for(int i=0;i<nums.size();i++){
            m[nums[i]]=i;
        }
        for(int i=0;i<nums.size();i++){
            int num= target - nums[i];
            if(m[num] && m[num]!=i){
                return {i, m[num]};
            }
        }
        return {};
    }
};

Complexity Analysis:

Time Complexity: O(n), for iterating through the array Space Complexity: O(n), for storing elements in map

No Comments Yet