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.
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)