File tree Expand file tree Collapse file tree
Sprint-1/JavaScript/calculateSumAndProduct Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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)
15+ * Explanation: The function iterates through the list of numbers twice,
16+ * once to calculate the sum and once to calculate the product.
17+ * Each iteration takes O(n) time, resulting in a total time complexity of O(n).
18+ * The space complexity is O(1) because we are using a constant amount of space to store the sum and product,
19+ * regardless of the size of the input list.
20+ *
21+ * Refactor:
22+ * I combined the two loops into a single loop
23+ * to calculate both the sum and product simultaneously.
1524 *
1625 * @param {Array<number> } numbers - Numbers to process
1726 * @returns {Object } Object containing running total and product
1827 */
1928export function calculateSumAndProduct ( numbers ) {
2029 let sum = 0 ;
21- for ( const num of numbers ) {
22- sum += num ;
23- }
24-
2530 let product = 1 ;
2631 for ( const num of numbers ) {
32+ sum += num ;
2733 product *= num ;
2834 }
2935
30- return {
31- sum : sum ,
32- product : product ,
33- } ;
36+ return { sum, product} ;
3437}
You can’t perform that action at this time.
0 commit comments