Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to find the two elements in an array whose sum is closest to zero in JavaScript

1 Answer

0 votes
function findClosestToZero(arr) {
    if (arr.length < 2) {
        console.log("arr must have at least two elements.");
        return;
    }

    // Step 1: Sort the arr
    let sortedArr = [...arr];
    sortedArr.sort((a, b) => a - b);

    let left = 0;
    let right = sortedArr.length - 1;
    let closestSum = Number.MAX_SAFE_INTEGER;
    let closestPair = [0, 0];

    // Step 2: Use two-indexed technique
    while (left < right) {
        let sum = sortedArr[left] + sortedArr[right];

        // Update closest sum and pair if needed
        if (Math.abs(sum) < Math.abs(closestSum)) {
            closestSum = sum;
            closestPair[0] = sortedArr[left];
            closestPair[1] = sortedArr[right];
        }

        // Move indexeds
        if (sum < 0) {
            left++; // Increase sum by moving left indexed
        } else {
            right--; // Decrease sum by moving right indexed
        }
    }

    // Output the result
    console.log(`The two elements whose sum is closest to zero are: 
                 ${closestPair[0]} and ${closestPair[1]} with a sum of ${closestSum}.`);
}

const arr = [23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31];

findClosestToZero(arr);


/*
run:

The two elements whose sum is closest to zero are: 
                 -88 and 90 with a sum of 2.

*/

 



answered Sep 13, 2025 by avibootz
edited Sep 13, 2025 by avibootz
...