Two Sum - LeetCode Easy

Two Sum - LeetCode Easy

Problem Link - https://leetcode.com/problems/two-sum/

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n=nums.size(); //finding the length of the dynamic array i.e., our vector
        unordered_map<int,int>mp; //creating a hashmap (A special type of block)
        for(int i=0;i<n;i++){ //Complexity - O(N)
            if(mp.find(target-nums[i])!=mp.end()){ //finding if our target - nums[i] exist in our hashmap
                return {mp[target-nums[i]],i}; 
            }
            else{
                mp[nums[i]]=i;   
            }
        }
        return {-1,-1}; // else printing -1
    }
};

Time Complexity - O(N) Space Complexity - O(N)

Trade off between time and space with respect to other approaches.

Vector : Vectors in C++ are sequence containers representing arrays that can change in size. They use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.

Hashmap : Hash maps, sometimes called dictionary or table, are known as unordered maps in C++. The C++ standard library's implementation of hash map is called std::unordered_map . std::unordered_map makes no guarantees about the order of its keys and their order can depend on when they are inserted into the map.

#hashmap

#concept

#unorderedmap

#c++ #cpp

#leetcode

#leetcodesolution