|
9 | 9 | * "product": 30 // 2 * 3 * 5 |
10 | 10 | * } |
11 | 11 | * |
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 |
15 | 15 | * |
16 | 16 | * @param {Array<number>} numbers - Numbers to process |
17 | 17 | * @returns {Object} Object containing running total and product |
18 | 18 | */ |
19 | 19 | 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 |
24 | 26 |
|
25 | | - let product = 1; |
| 27 | + // Single pass through array: O(n) time complexity |
26 | 28 | for (const num of numbers) { |
27 | | - product *= num; |
| 29 | + sum += num; // O(1) operation per element |
| 30 | + product *= num; // O(1) operation per element |
28 | 31 | } |
29 | 32 |
|
30 | | - return { |
31 | | - sum: sum, |
32 | | - product: product, |
33 | | - }; |
| 33 | + // Return optimized object syntax: O(1) space |
| 34 | + return { sum, product }; |
34 | 35 | } |
| 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