two number sum code example
Example 1: two sum javascript
var twoSum = function(nums, target) {
var hash = {};
for(let i=0; i<=nums.length; i++){
var currentNumber = nums[i];
var requiredNumber = target - currentNumber;
const index2 = hash[requiredNumber];
if(index2 != undefined) {
return [index2, i]
} else {
hash[currentNumber] = i;
}
}
};
Example 2: Sum of all the multiples of 3 or 5
const findSum = n => {
let countArr = []
for(let i = 0; i <= n; i++) countArr.push(i)
let finalArr = countArr.map(digit => {
if(digit % 3 === 0 || digit % 5 === 0) return digit
else return 0
}).reduce((acc , curr) => acc + curr)
return finalArr
}
console.log(findSum(10))
Example 3: find pair in unsorted array which gives sum x
#include <bits/stdc++.h>
using namespace std;
bool hasArrayTwoCandidates(int A[], int arr_size,
int sum)
{
int l, r;
sort(A, A + arr_size);
l = 0;
r = arr_size - 1;
while (l < r) {
if (A[l] + A[r] == sum)
return 1;
else if (A[l] + A[r] < sum)
l++;
else
r--;
}
return 0;
}
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
if (hasArrayTwoCandidates(A, arr_size, n))
cout << "Array has two elements with given sum";
else
cout << "Array doesn't have two elements with given sum";
return 0;
}