Skip to content

Commit 0313954

Browse files
author
Fatma Degirmenci
committed
Refactor calculateSumAndProduct to use a single loop for sum and product
1 parent de683df commit 0313954

1 file changed

Lines changed: 6 additions & 8 deletions

File tree

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

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,19 @@
99
* "product": 30 // 2 * 3 * 5
1010
* }
1111
*
12-
* Time Complexity:
13-
* Space Complexity:
14-
* Optimal Time Complexity:
15-
*
12+
* Time Complexity: There are two separate loops. Total operation O(n)+O(n) ---> O(n)
13+
* Space Complexity:We are only using two variables sum and product --->O(1)
14+
* Optimal Time Complexity:To calculate sum and product, every element must be visited at least once, so the optimal time complexity is O(n)
15+
* Refactor Note: We can combine both calculations into a single loop for cleaner and more readable code
16+
*
1617
* @param {Array<number>} numbers - Numbers to process
1718
* @returns {Object} Object containing running total and product
1819
*/
1920
export function calculateSumAndProduct(numbers) {
2021
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2522
let product = 1;
2623
for (const num of numbers) {
24+
sum += num;
2725
product *= num;
2826
}
2927

0 commit comments

Comments
 (0)