Javascript SumOfTwo

I have a function getPairs which gets array and sum as a param and returns all possible pairs. But I have a problem with their position in the array and deleting it in some different input param

function getPairs (arr, sum) {
if (!arr.length) return []

        const result = []
        const numObject = {}

        for (let i = 0; i < arr.length; i++) {
            numObject[arr[i]] = i;
        }

        for (let i = 0; i < arr.length; i++) {
            const diff = sum - arr[i];

            if (numObject[diff] && numObject[diff] !== i) {
                result.push([diff, arr[i]])
                arr.splice(arr.indexOf(diff), 1)
                arr.splice(i, 1)
            }
        }
        

        return result
    }

    console.log(getPairs([], 0))
    console.log(getPairs([22, 3, 5, 0, 2, 2], 5))
    console.log(getPairs([-5, 33, 2, 2, 3, 5, 0, 10, 3], 5))
    console.log(getPairs([5, 5, 5, 0, 0, 0, 5], 5))
    console.log(getPairs([3, 3, 6, 0], 6))

    input: ([22, 3, 5, 0, 2, 2], 5)
    resutls must be: [[3, 2], [5, 0]]
    i get:           [[2, 3], [3, 2]]
    
    input: ([-5, 33, 2, 2, 3, 5, 0, 10, 3], 5)
    resutls must be: [[-5, 10], [2, 3], [2, 3], [5, 0]]
    i get:           [[10, -5], [3, 2], [0, 5]]

    input: ([5, 5, 5, 0, 0, 0, 5], 5)
    resutls must be: [[5, 0], [5, 0], [5, 0]]
    i get:           [[0, 5], [0, 5], [0, 5]]
 
    input: ([3, 3, 6, 0], 6)
    resutls must be: [[3, 3], [6, 0]]
    i get:   [[3, 3], [6, 0]]

Thanks!

1 thought on “Javascript SumOfTwo”

  1. You can try using Binary Search (the input array will be have to be sorted though, so time complexity will be O(nlogn)

    const getPairs = (arr,sum)=>{
        let low=0
        let high=arr.length-1;
        let pairs=[]
        arr.sort(function(a, b){return a-b})// Sort in Ascending for Binary Search
        while(low<high){
            if(arr[low]+arr[high]==sum){
                pairs.push([arr[low],arr[high]])
            }
            if(arr[low]+arr[high]>sum){
                high-=1
            }else{
                low+=1
            }
        }
        return pairs
    }
    

    If you want to get rid of duplicate pairs, you will have to add them to set or use an hashmap(object)

    Reply

Leave a Comment