Skip to content

Commit 620c969

Browse files
committed
function refactored and explained complexity
1 parent f13588d commit 620c969

1 file changed

Lines changed: 8 additions & 8 deletions

File tree

‎Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,24 @@
99
* "product": 30 // 2 * 3 * 5
1010
* }
1111
*
12-
* Time Complexity:
13-
* Space Complexity:
14-
* Optimal Time Complexity:
12+
* Time Complexity: O(n) - one loop through the list (the original used two loops, 2n steps, which is also O(n)).
13+
* Space Complexity: O(1) - only two variables (sum, product), regardless of input size
14+
* Optimal Time Complexity: O(n) - every number must be read at least once, so we can't do better than linear time
15+
*
16+
* Refactor: the complexity can't be reduced, but merging the two loops into
17+
* one makes the code cleaner and does half the steps.
1518
*
1619
* @param {Array<number>} numbers - Numbers to process
1720
* @returns {Object} Object containing running total and product
1821
*/
1922
export function calculateSumAndProduct(numbers) {
2023
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2524
let product = 1;
2625
for (const num of numbers) {
26+
sum += num;
2727
product *= num;
2828
}
29-
29+
3030
return {
3131
sum: sum,
3232
product: product,

0 commit comments

Comments
 (0)