Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda