Skip to content

Commit 6c97572

Browse files
committed
analyse and refactor calculateSumAndProduct
1 parent e718fb4 commit 6c97572

1 file changed

Lines changed: 14 additions & 11 deletions

File tree

Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,29 @@
99
* "product": 30 // 2 * 3 * 5
1010
* }
1111
*
12-
* Time Complexity:
13-
* Space Complexity:
14-
* Optimal Time Complexity:
12+
* Time Complexity: O(n)
13+
* Space Complexity: O(1)
14+
* Optimal Time Complexity: O(n)
15+
* Explanation: The function iterates through the list of numbers twice,
16+
* once to calculate the sum and once to calculate the product.
17+
* Each iteration takes O(n) time, resulting in a total time complexity of O(n).
18+
* The space complexity is O(1) because we are using a constant amount of space to store the sum and product,
19+
* regardless of the size of the input list.
20+
*
21+
* Refactor:
22+
* I combined the two loops into a single loop
23+
* to calculate both the sum and product simultaneously.
1524
*
1625
* @param {Array<number>} numbers - Numbers to process
1726
* @returns {Object} Object containing running total and product
1827
*/
1928
export function calculateSumAndProduct(numbers) {
2029
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2530
let product = 1;
2631
for (const num of numbers) {
32+
sum += num;
2733
product *= num;
2834
}
2935

30-
return {
31-
sum: sum,
32-
product: product,
33-
};
36+
return {sum,product};
3437
}

0 commit comments

Comments
 (0)