Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
hasPairsWithSum Google Interview Question

I solved this problem by iterating through the array then find the item when the sum equals to array[i] + item returning true otherwise returning false.

My Question is => How I can return the indices of those numbers that add up to sum not just true? Using the same code below:

function hasPairsWithSum(array,sum) {
  for (let i = 0; i < array.length; i++) {
    if (array.find((item) => {return sum === array[i] + item}
    ));
    return true;
  };
  return false;
};
console.log(hasPairsWithSum([1,2,4,4],8))

Note: Time complexity must be less than O(n ^ 2).

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

JavaScript O(n) Solution.

function hasPairsWithSum(array, sum) {
  const map = new Map ();
  for(let i = 0; i < array.length; i++) {
    let currVal = array[i];
    if (map.has(currVal)) {
      return [map.get(currVal),i]
    }
    // difference value = sum - current value
    let diff = sum - currVal
    map.set(diff,i)
  }
};
console.log(hasPairsWithSum([2,2,4,4], 8))
about 4 years ago · Juan Pablo Isaza Report

0

You have to iterate over the array elements checking at every iteration for every element of the array (except the last one) all the elements at the right of it like below:

function findIndexes(array, sum) {
    const result = [];

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

    return result;
}

console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));

Update:

It is possible to obtain a linear O(n) complexity using an auxiliary Map structure associating an integer value as key with as a value the list containing all the indexes of the elements in the array equal to the integer key like below:

function findIndexes(array, sum) {
    const map = new Map();
    const result = [];

    for (let i = 0; i < array.length; ++i) {
        const a = array[i];
        const b = sum - a;
        
        if (map.has(b)) {
            for (const index of map.get(b)) {
                result.push([index, i]);
            }
        }
        
        const l = map.has(a) ? map.get(a) : [];
        l.push(i);
        map.set(a, l);      
    }

    return result;
}


console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));
console.log(findIndexes([1, 1, 1], 2));

about 4 years ago · Juan Pablo Isaza Report

0

O(n) Soln ... using math concept a+b = n then if a is present in our array then need to find b = n - a is present or not ..

def hasPairsWithSum(array,sum):
    d = {} 
    for i in range(len(array)):
        if(array[i] in d):
            d[array[i]].append(i)
        else:
            d[array[i]] = [i]
    ans  = []
    for i in range(len(array)):
        val = sum - array[i]
        if(val in d):
            if(d[val][0] == i):
                if(len(d[val])  > 1):
                    ans.append((i,d[val][1]))
                    break
                else:
                    continue
            else:
                ans.append((i,d[val][0]))
                break
    return ans
print(hasPairsWithSum([4, 4, 4, 4], 8))

O(nlogn) soln ....just store the index with elements .. then sort it by their values .. next step run a loop with complexity of O(n) [concept : Two pointers]

def hasPairsWithSum(array,sum):
    arr = []
    for i in range(len(array)):
        arr.append((array[i],i))
    arr.sort()
    i = 0
    j = len(array)-1
    ans = []
    while(i<j):
        tmp_sum = arr[i][0] + arr[j][0]
        if(tmp_sum == sum):
            ans.append((arr[i][1] , arr[j][1]))
            #add your logic if you want to find all possible indexes instead of break
            break
        elif(tmp_sum < sum):
            i = i + 1
        elif(tmp_sum > sum):
            j = j - 1
    return ans
print(hasPairsWithSum([1,2,4,4],8))
  • note : if you want to find all possible soln then these approaches will not work either add you own logic in while loop or another approach is use binary search with traversal on every element and store the indexes in set (worst case this will be O(n^2) as we have to find all possible values) Eg: [4,4,4,4,4,4] , sum = 8 and you want to print all possible indexes then we end up running it upto n^2 (why? reason: total possible solns. are 5+4+3+2+1 = n*(n-1)/2 ≈ n^2)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!