Skip to content

Commit 070514b

Browse files
committed
sumandproduct func complexity analysis + refactoring for better efficiency
1 parent 134e683 commit 070514b

1 file changed

Lines changed: 28 additions & 5 deletions

File tree

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

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,40 @@
1616
* @param {Array<number>} numbers - Numbers to process
1717
* @returns {Object} Object containing running total and product
1818
*/
19+
// export function calculateSumAndProduct(numbers) {
20+
// let sum = 0;
21+
// for (const num of numbers) {
22+
// sum += num;
23+
// }
24+
25+
// let product = 1;
26+
// for (const num of numbers) {
27+
// product *= num;
28+
// }
29+
30+
// return {
31+
// sum: sum,
32+
// product: product,
33+
// };
34+
// }
35+
36+
//My Analysis report
37+
// the function have two loops which looks similar and can be simplified, they makes the time complexity of the function
38+
// a numbers.length times which is O(n). for the two loops time complexity becomes O(n) + O(n) = O(2n)
39+
// after looping it stores the results on the two variables i.e. sum and product which have O(1) + O(1) space complexity.
40+
// the space complexity related to arr size is unavoidable/ unchangeable and is optimal in this case , which is O(n)
41+
// And The area of inefficiency for this code is on the loop (i.e. looping twice)
42+
43+
//refactored code for better efficiency.
44+
//what i have done here is i use a single loop to change the efficiency from o(2n) to o(n)
45+
1946
export function calculateSumAndProduct(numbers) {
2047
let sum = 0;
21-
for (const num of numbers) {
22-
sum += num;
23-
}
24-
2548
let product = 1;
2649
for (const num of numbers) {
50+
sum += num;
2751
product *= num;
2852
}
29-
3053
return {
3154
sum: sum,
3255
product: product,

0 commit comments

Comments
 (0)