Two Sum LeetCode Solution

Here, We see Two Sum LeetCode problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Two Sum LeetCode Solution

Two Sum LeetCode Solution

Problem Statement ->

Given an array of integer 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]
Explanation: 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]

Two Sum Leetcode Solution C++ ->

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> cache; vector<int> answer; for (size_t i = 0; i < nums.size(); ++i) { int needed_num = target - nums[i]; if (cache.find(needed_num) != cache.end()) { // We found it answer.push_back(cache[needed_num]); answer.push_back(i); return answer; } else { // Didn't find it cache.insert(make_pair(nums[i], i)); } } return answer; } };
Code language: C++ (cpp)

Two Sum Leetcode Solution Java ->

class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] == target - nums[i]) { return new int[] { i, j }; } } } // In case there is no solution, we'll just return null return null; } }
Code language: Java (java)

Two Sum Leetcode Solution JavaScript ->

var twoSum = function(nums, target) { let map = new Map; for (var i = 0; i < nums.length; i++) { let complement = target - nums[i]; if (map.has(complement)) { return [map.get(complement), i] } map.set(nums[i], i); } };
Code language: JavaScript (javascript)

Two Sum Leetcode Solution Python ->

class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[j] == target - nums[i]: return [i, j]
Code language: Python (python)