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
Left right subarray sum product - JavaScript
We are required to write a JavaScript function that takes in an array of numbers of length N (N should be even) and divides the array into two sub-arrays (left and right) containing N/2 elements each, calculates the sum of each sub-array, and then multiplies both sums together.
For example: If the input array is:
const arr = [1, 2, 3, 4]
The calculation would be:
Left subarray: [1, 2] ? sum = 1 + 2 = 3 Right subarray: [3, 4] ? sum = 3 + 4 = 7 Product: 3 × 7 = 21
Example
Following is the complete implementation:
const arr = [1, 2, 3, 4];
const subArrayProduct = arr => {
const { length: l } = arr;
const creds = arr.reduce((acc, val, ind) => {
let { left, right } = acc;
if(ind < l/2){
left += val;
}else{
right += val;
}
return { left, right };
}, {
left: 0,
right: 0
});
return creds.left * creds.right;
};
console.log(subArrayProduct(arr));
Output
21
Alternative Approach Using Array Slicing
Here's a simpler approach using array slicing methods:
const arr = [1, 2, 3, 4, 5, 6];
const subArrayProductSlice = arr => {
const mid = arr.length / 2;
const leftSum = arr.slice(0, mid).reduce((sum, val) => sum + val, 0);
const rightSum = arr.slice(mid).reduce((sum, val) => sum + val, 0);
return leftSum * rightSum;
};
console.log(subArrayProductSlice(arr));
63
How It Works
The first approach uses reduce() to iterate through the array once, accumulating sums for left and right halves based on the index. The second approach splits the array into two halves using slice() and calculates their sums separately.
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Single reduce() | O(n) | O(1) | Moderate |
| Array slicing | O(n) | O(n) | High |
Conclusion
Both approaches effectively solve the problem of calculating the product of left and right subarray sums. The reduce method is more memory-efficient, while array slicing offers better code readability.
