Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implementing partial sum over an array using JavaScript
We need to write a JavaScript function that takes an array of numbers and returns a new array where each element represents the sum of all elements from that position to the end of the original array (including the current element).
Problem
Given an array of numbers, construct a new array where each corresponding element is the sum of all elements from that position to the right (including itself) in the input array.
Example Input and Expected Output
For array [5, 6, 1, 3, 8, 11], the partial sum array should be:
- Position 0: 5 + 6 + 1 + 3 + 8 + 11 = 34
- Position 1: 6 + 1 + 3 + 8 + 11 = 29
- Position 2: 1 + 3 + 8 + 11 = 23
- And so on...
Solution
const arr = [5, 6, 1, 3, 8, 11];
const partialSum = (arr = []) => {
if (arr.length === 0) {
return [];
}
let sum = arr.reduce((acc, val) => acc + val);
const res = [];
for (let i = 0; i < arr.length; i++) {
res.push(sum);
sum -= arr[i];
}
return res;
};
console.log("Original array:", arr);
console.log("Partial sum array:", partialSum(arr));
Original array: [ 5, 6, 1, 3, 8, 11 ] Partial sum array: [ 34, 29, 23, 22, 19, 11 ]
How It Works
The algorithm works efficiently in two steps:
-
Calculate total sum: First, we find the sum of all elements using
reduce() - Build result array: We iterate through the array, adding the current sum to results and then subtracting the current element from the sum for the next iteration
Alternative Approach: Using Nested Loops
const partialSumNested = (arr = []) => {
if (arr.length === 0) {
return [];
}
const res = [];
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
}
res.push(sum);
}
return res;
};
const testArray = [2, 4, 6, 8];
console.log("Using nested loops:", partialSumNested(testArray));
Using nested loops: [ 20, 18, 14, 8 ]
Comparison
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Optimized (single loop) | O(n) | O(1) | Better |
| Nested loops | O(n²) | O(1) | Less efficient |
Conclusion
The optimized solution using a single loop is more efficient with O(n) time complexity. It calculates the total sum once and then subtracts elements progressively to build the partial sum array.
