Skip to content

Commit 410e893

Browse files
committed
feat: Optimise calculateSumAndProduct function
1 parent e718fb4 commit 410e893

1 file changed

Lines changed: 8 additions & 7 deletions

File tree

Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,22 @@
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)
1515
*
1616
* @param {Array<number>} numbers - Numbers to process
1717
* @returns {Object} Object containing running total and product
1818
*/
1919
export function calculateSumAndProduct(numbers) {
2020
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2521
let product = 1;
22+
23+
// Initial code looped twice through the array, i.e. 2 operations (n + n) = O(2n)operations => O(n). Limiting the loop to just one operation makes it n operation => O(n).
24+
// The space complexity is constant as the variables do not grow when the function is called.
25+
2626
for (const num of numbers) {
27+
sum += num;
2728
product *= num;
2829
}
2930

0 commit comments

Comments
 (0)