Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda