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

193
Visualizações
What is the entire time complexity of this recursive function with nested operations?

I have the following top-down recursive function which calculates all of the different ways we can sum together numbers from numbers such that they equal targetSum. I am now trying to determine the time complexity of this problem exactly.

const allWays = (targetSum, numbers) => {

  const fn = (remainder, startIndex) => {
    if (remainder === 0) return [[]];

    const result = [];
    for (let i = startIndex; i < numbers.length; i += 1) {
      const num = numbers[i];
      if (remainder - num < 0) continue;

      const remainderWays = fn(remainder - num, i);
      const targetWays = remainderWays.map((way) => [num, ...way]);
      result.push(...targetWays);
    }

    return result;
  };

  return fn(targetSum, 0);
};

If we let the m be the size of targetSum and we let n be the length of numbers, then the recursion tree should have a height of m and a branching factor of n giving it a time complexity of O(n^m).

While I understand that this exponential factor will dominate all other time complexities, I would still like to know what the .map, and two spread operators add to the runtime.

I cant seem to wrap my head around what the time complexity of this

const targetWays = remainderWays.map((way) => [num, ...way]);
result.push(...targetWays);

should be.

Any help is appreciated! Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For both #map and #push, the time complexity would be O(o) since #map will iterate through the list/array and push will add inidividual element at the end of the list by iterating over targetWays. So both would be O(o) operation. (Considering o is length of result size)

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