Two Sum. (Leetcode Easy Problem) - by Sukanya Bharati - Nerd For Tech - Medium
Two Sum. (Leetcode Easy Problem) - by Sukanya Bharati - Nerd For Tech - Medium
Save
1. Two Sum
(Leetcode easy problem)
77
You may assume that each input would have exactly one solution, and
Open in app Get started
you may not use the same element twice.
Sign in to Medium with Google
Output: [0,1]
Example 2:
Output: [1,2]
Example 3:
Output: [0,1]
Approach :
{
Open in app Get started
for(int j = i+1;j<nums.size();j++)
if(nums[i]+nums[j]==target)
...
23_Pratyasha Kar
}
[email protected]
}
PRATYASHA KAR
Time Complexity - O(n*n)
[email protected]
Space Complexity - O(1)
2. Using Hashmap
Code is as follows :
class Solution {
public:
vector<int>ans;
unordered_map<int,int>m;
for(int i=0;i<nums.size();i++)
ans.push_back(m.find(val)->second);
ans.push_back(i);
break;
m.insert(pair<int,int>(nums[i],i)); // in
case the above criteria is not satisfied I will keep
inserting the element in the hashmap Open
in app Get started
}
Sign in to Medium with Google
return ans;
}; 23_Pratyasha Kar
[email protected]
PRATYASHA KAR
[email protected]
Since you enjoyed reading my blog , why not buy me a coffee and
supoort my work here!!
https://www.buymeacoffee.com/sukanyabharati ☕
23_Pratyasha Kar
[email protected]
PRATYASHA KAR
Sign up for NFT Weekly Digest
[email protected]
By Nerd For Tech
Subscribe to our weekly News Letter to receive top stories from the Industry Professionals around
the world Take a look.
Your email
By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more
information about our privacy practices.