Skip to content

Commit 019519b

Browse files
refactor: reduce calculateSumAndProduct to single loop
1 parent e718fb4 commit 019519b

2 files changed

Lines changed: 12 additions & 19 deletions

File tree

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

Lines changed: 5 additions & 7 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:
12+
* Time Complexity: O(n) - two passes through the array
13+
* Space Complexity: O(1) - only two variables
14+
* Optimal Time Complexity: O(n) - single pass through the array
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+
2623
for (const num of numbers) {
24+
sum += num;
2725
product *= num;
2826
}
2927

‎Sprint-1/Python/calculate_sum_and_product/calculate_sum_and_product.py‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,15 @@ def calculate_sum_and_product(input_numbers: List[int]) -> Dict[str, int]:
1212
"sum": 10, // 2 + 3 + 5
1313
"product": 30 // 2 * 3 * 5
1414
}
15-
Time Complexity:
16-
Space Complexity:
17-
Optimal time complexity:
15+
Time Complexity: O(n) - two passes through the list
16+
Space Complexity: O(1) - only two variables
17+
Optimal time complexity: O(n) - single pass through the list
1818
"""
19-
# Edge case: empty list
20-
if not input_numbers:
21-
return {"sum": 0, "product": 1}
22-
23-
sum = 0
24-
for current_number in input_numbers:
25-
sum += current_number
26-
19+
total = 0
2720
product = 1
21+
2822
for current_number in input_numbers:
23+
total += current_number
2924
product *= current_number
3025

31-
return {"sum": sum, "product": product}
26+
return {"sum": total, "product": product}

0 commit comments

Comments
 (0)