Skip to content

Commit 4f74f0c

Browse files
committed
refactor: optimize calculateSumAndProduct to single-pass algorithm
1 parent eebcb62 commit 4f74f0c

1 file changed

Lines changed: 40 additions & 13 deletions

File tree

Sprint-1/JavaScript/calculateSumAndProduct/calculateSumAndProduct.js

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,53 @@
99
* "product": 30 // 2 * 3 * 5
1010
* }
1111
*
12-
* Time Complexity:
13-
* Space Complexity:
14-
* Optimal Time Complexity:
12+
* Time Complexity: O(n) - Single pass through the array
13+
* Space Complexity: O(1) - Only using constant extra space
14+
* Optimal Time Complexity: O(n) - Cannot do better than linear time
1515
*
1616
* @param {Array<number>} numbers - Numbers to process
1717
* @returns {Object} Object containing running total and product
1818
*/
1919
export function calculateSumAndProduct(numbers) {
20-
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
20+
// OPTIMIZED IMPLEMENTATION: Single pass algorithm
21+
// Previous implementation used two separate loops (2n operations)
22+
// This version combines both calculations in one loop (n operations)
23+
24+
let sum = 0; // O(1) space
25+
let product = 1; // O(1) space
2426

25-
let product = 1;
27+
// Single pass through array: O(n) time complexity
2628
for (const num of numbers) {
27-
product *= num;
29+
sum += num; // O(1) operation per element
30+
product *= num; // O(1) operation per element
2831
}
2932

30-
return {
31-
sum: sum,
32-
product: product,
33-
};
33+
// Return optimized object syntax: O(1) space
34+
return { sum, product };
3435
}
36+
37+
/*
38+
* ORIGINAL IMPLEMENTATION (for comparison):
39+
*
40+
* export function calculateSumAndProduct(numbers) {
41+
* let sum = 0;
42+
* for (const num of numbers) { // First pass: O(n)
43+
* sum += num;
44+
* }
45+
*
46+
* let product = 1;
47+
* for (const num of numbers) { // Second pass: O(n)
48+
* product *= num;
49+
* }
50+
*
51+
* return { // Total: O(2n) = O(n) time
52+
* sum: sum, // O(1) space
53+
* product: product,
54+
* };
55+
* }
56+
*
57+
* IMPROVEMENTS MADE:
58+
* 1. Reduced from 2n to n operations (50% fewer iterations)
59+
* 2. Better cache locality (single pass through memory)
60+
* 3. Same O(n) time complexity but with better constant factors
61+
*/

0 commit comments

Comments
 (0)