Search This Blog

2023/09/10

Javascript:In one dimesional numeric array find pairs of zero sum element

Problem Statement:

For given one dimensional array of numbers find pair of elements whose sum is zero.
e.g.
if array is
[-4, -10, -8, -3, 3, 4, 5, -5, 7, 8, -7]
then solution should be
[[-4,4],[-8,8],[-3,3],[5,-5],[7,-7]]


Solution (Way 1):
function findPairsWithSumZero(arr) {
var result = [];

//sort
arr = arr.sort((a, b) => {
return a - b;
});

let left = 0;
let right = arr.length - 1;

while (left < right) {
let sum = arr[left] + arr[right];
if (sum == 0) {
result.push([arr[left], arr[right]]);
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}

return result;
}

const myarr = [-4, -10, -8, -3, 3, 4, 5, -5, 7, 8, -7];
const result = findPairsWithSumZero(myarr);
console.log(result);

Output:
[ [ -8, 8 ], [ -7, 7 ], [ -5, 5 ], [ -4, 4 ], [ -3, 3 ] ]


Solution (Way 2):
function findPairsWithSumZero(arr) {
var result = [];

//sort
arr = arr.sort((a, b) => {
return a - b;
});

//loop
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == 0) {
result.push([arr[i], arr[j]]);
}
}
}

return result;
}

const myarr = [-4, -10, -8, -3, 3, 4, 5, -5, 7, 8, -7];
const result = findPairsWithSumZero(myarr);
console.log(result);
Output:
[ [ -8, 8 ], [ -7, 7 ], [ -5, 5 ], [ -4, 4 ], [ -3, 3 ] ]

Solution (Way 3):
function findPairsWithSumZero(arr) {
const seenNumbers = new Set();
const pairs = [];

for (const num of arr) {
const complement = -num;

if (seenNumbers.has(complement)) {
pairs.push([num, complement]);
}

seenNumbers.add(num);
}
return pairs;
}

const myarr = [-4, -10, -8, -3, 3, 4, 5, -5, 7, 8, -7];
const result = findPairsWithSumZero(myarr);
console.log(result);
Output:
[ [ 3, -3 ], [ 4, -4 ], [ -5, 5 ], [ 8, -8 ], [ -7, 7 ] ]


No comments:

Post a Comment