-
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcalculateSumAndProduct.js
More file actions
34 lines (32 loc) · 983 Bytes
/
calculateSumAndProduct.js
File metadata and controls
34 lines (32 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Calculate the sum and product of integers in a list
*
* Note: the "sum" is every number added together
* and the "product" is every number multiplied together
* so for example: [2, 3, 5] would return
* {
* "sum": 10, // 2 + 3 + 5
* "product": 30 // 2 * 3 * 5
* }
*
* Time Complexity:O(n) because constant multipliers are ignored in Big-O notation.
* Space Complexity:O(1) no extra space used that grows with input
* Optimal Time Complexity:O(n) must at least visit each number once
*
* @param {Array<number>} numbers - Numbers to process
* @returns {Object} Object containing running total and product
*/
// here we are using 2 loops one for sum and other for product
// but we can do it only in one loop so code will be more simple and faster
export function calculateSumAndProduct(numbers) {
let sum = 0;
let product = 1;
for (const num of numbers) {
sum += num;
product *= num;
}
return {
sum: sum,
product: product,
};
}