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

179
Views
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 answers
Answer question

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 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!