Two Sum Leetcode Solution
Two Sum Leetcode Problem :
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.return [0, 1]..
Two Sum Leetcode Solution :
Constraints :
- 2 <= nums.length <= 10^4
- -10^9 <= nums[i] <=10^9
- -10^9 <= target <= 10^9
- Only one valid answer exists.
Example 1:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 2:
Input: nums = [3,3], target = 6
Output: [0,1]
In the “Two Sum” problem, you are given an array of integers nums
and an integer target
. The goal is to find two numbers in the array such that their sum equals the target
. Here are the key points for the given constraints and examples:
Constraints:
- The length of the nums array is between 2 and 10,000.
- The values in the nums array can range from -1,000,000,000 to 1,000,000,000.
- The target value can also range from -1,000,000,000 to 1,000,000,000.
- There is exactly one valid solution.
Approach :
For Solving two sum Leetcode Problem we can use following procedure :
- A hashmap which contain the element of the array along with its indices.
- Then we can traverse the array such that target – particular element will find the hashmap which return the indices respectively.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: vectortwoSum(vector & nums, int target) { // declaration of map unordered_map mpp; // inserting value of array along with its index for(int i=0;i< nums.size();i++){ mpp[nums[i]]= i; } // check if value and target - value present in the map for(auto it : mpp){ if(mpp.find(target - it.fist) != mpp.end()){ return {it.first, mpp[target - it.first]}; } } return {-1,-1}; } };
import java.util.HashMap; import java.util.Map; class Solution { public int[] twoSum(int[] nums, int target) { Mapmpp = new HashMap<>(); for(int i=0; i entry : mpp.entrySet()){ int key = entry.getKey(); int value = entry.getValue(); if(mpp.containsKey(target - key)){ return new int[]{key, mpp.get(target - key)}; } } return new int[]{-1, -1}; } }
class Solution: def twoSum(self, nums, target): mpp = {} for i in range(len(nums)): mpp[nums[i]] = i for key, value in mpp.items(): if (target - key) in mpp: return [key, mpp[target - key]] return [-1, -1]
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment