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
Accumulating array elements to form new array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a number, num, (num ? length of array) as the second argument.
Our function should add up each contiguous subarray of length num of the array arr to form corresponding elements of new array and finally return that new array.
Problem Example
For example, if the input to the function is:
const arr = [1, 2, 3, 4, 5, 6]; const num = 2;
Then the output should be:
[3, 5, 7, 9, 11]
Output Explanation
Because 1 + 2 = 3, 2 + 3 = 5, 3 + 4 = 7, 4 + 5 = 9, and 5 + 6 = 11.
Solution Using Sliding Window Technique
The most efficient approach uses the sliding window technique. Instead of recalculating the sum for each subarray, we slide the window by removing the leftmost element and adding the new rightmost element.
const arr = [1, 2, 3, 4, 5, 6];
const num = 2;
const accumulateArray = (arr = [], num = 1) => {
const res = [];
let sum = 0, right = 0, left = 0;
// Calculate sum of first window
for(; right
[3, 5, 7, 9, 11]
Alternative Solution Using Array Methods
Here's a more readable approach using array methods:
const arr = [1, 2, 3, 4, 5, 6];
const num = 3;
const accumulateArraySimple = (arr, num) => {
const result = [];
for(let i = 0; i acc + val, 0);
result.push(sum);
}
return result;
};
console.log(accumulateArraySimple(arr, num));
[6, 9, 12, 15]
How It Works
The sliding window approach works in two phases:
-
Initialize: Calculate the sum of the first subarray of length num
-
Slide: For each subsequent position, subtract the element going out of the window and add the new element entering the window
This reduces time complexity from O(n×num) to O(n), making it much more efficient for large arrays.
Conclusion
The sliding window technique provides an optimal solution for accumulating contiguous subarrays. It maintains efficiency by reusing previous calculations instead of recalculating sums from scratch.
