Algorithm


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

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]
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]

 

Constraints:

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

 

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming

var twoSum = function(nums, target) {
  const hashmap = {};
  for (let i = 0; i  <  nums.length; i++) {
    const diff = target - nums[i];

    // If the difference is in the hashmap, return the indices.
    if (diff in hashmap) { // or, hashmap[diff] !== undefined
      return [hashmap[diff], i];
    }

    // Otherwise, add the current number to the hashmap.
    hashmap[nums[i]] = i;
  }

  return [];
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
[2,7,11,15]
9

Output

x
+
cmd
[0,1]

#2 Code Example with C Programming

Code - C Programming


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int *indices = malloc(sizeof(int) * 2);
    *returnSize = 2;
    for (int i = 0; i  <  numsSize; i++) {
        for (int j = i + 1; j  <  numsSize; j++) {
            if (nums[i] + nums[j] == target) {
                indices[0] = i;
                indices[1] = j;
                return indices;
            }
        }
    }
    return indices;
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map map = new HashMap<>();
        for (int i = 0; i  <  nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}



This solution uses a hash map to store the indices of the numbers as they are processed. It iterates through the input array and for each number, it checks if the hash map contains the target minus the current number. If it does, it returns an array with the indices of the two numbers. If the loop completes without finding a solution, it throws an exception.

I hope this helps! Let me know if you have any questions. Copy The Code & Try With Live Editor

#4 Code Example with Python Programming

Code - Python Programming


class Solution:
    def twoSum(self, nums, target):
        nums_hash = {}
        for i in range(len(nums)):
            if target - nums[i] in nums_hash: 
                return [nums_hash[target - nums[i]], i]
            nums_hash[nums[i]] = i
Copy The Code & Try With Live Editor

#5 Code Example with C# Programming

Code - C# Programming


namespace LeetCode
{
    using System.Collections.Generic;

    public class _001_TwoSum
    {
        public int[] TwoSum(int[] nums, int target)
        {
            var dic = new Dictionary < int, int>();

            for (int i = 0; i  <  nums.Length; i++)
            {
                if (dic.ContainsKey(nums[i]))
                    return new int[] { dic[nums[i]], i };
                else
                    dic[target - nums[i]] = i;
            }

            return new int[] { };
        }
    }
}
Copy The Code & Try With Live Editor

#6 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map < int, int>m;
        for(int i = 0; i  <  nums.size(); i++){
            if(m.count(target - nums[i])) return {m[target - nums[i]], i};
            m[nums[i]] = i;
        }
    }
};

Copy The Code & Try With Live Editor
Advertisements

Demonstration


This solution uses a brute force approach to find the indices of the two numbers in the input array that add up to the target. It does this by using a nested loop to iterate over all pairs of numbers in the array and check if their sum is equal to the target. If it is, it stores the indices in an array and returns it.

I hope this helps! Let me know if you have any questions.

 

Leetcode - Two sum problem solution in JavaScript

Next
#02 Leetcode Add two numbers solution in JavaScript, C, PHP, C++, Java, C#, Python Programming, PHP, Python