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
Sum of All Possible Odd Length Subarrays in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the only argument.
The function should first permute all possible subarrays from the original array that have an odd length. And then the function should find the combined sum of all the elements of those subarrays and return the sum.
For example, if the input array is:
const arr = [1, 2, 3];
Then the output should be:
const output = 12;
Because the desired subarrays are [1], [2], [3], [1, 2, 3] with sums 1 + 2 + 3 + 6 = 12.
How It Works
The algorithm uses nested loops to generate all possible subarrays. For each starting position, it extends the subarray one element at a time, checking if the current length is odd before adding the sum to the result.
Example
Following is the code:
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3, 4, 5, 6];
const sumOfOddLengthSubarrays = (arr = []) => {
let res = 0;
for(let i = 0; i
12
98
Step-by-Step Breakdown
Let's trace through the algorithm with array [1, 2, 3]:
const arr = [1, 2, 3];
let oddSubarrays = [];
// Generate all subarrays and filter odd-length ones
for(let i = 0; i a+b)}`);
}
}
}
Subarray: [1], Length: 1, Sum: 1
Subarray: [1,2,3], Length: 3, Sum: 6
Subarray: [2], Length: 1, Sum: 2
Subarray: [3], Length: 1, Sum: 3
Optimized Approach
Here's an alternative mathematical approach that calculates how many times each element appears in odd-length subarrays:
const sumOfOddLengthSubarraysOptimized = (arr) => {
let result = 0;
const n = arr.length;
for(let i = 0; i
Element 1 appears in 2 odd-length subarrays
Element 2 appears in 3 odd-length subarrays
Element 3 appears in 2 odd-length subarrays
Optimized result: 12
Comparison
| Approach | Time Complexity | Space Complexity | Description |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Generate all subarrays, sum odd-length ones |
| Mathematical | O(n) | O(1) | Calculate contribution of each element |
Conclusion
Both approaches solve the problem effectively. The nested loop method is more intuitive, while the mathematical approach offers better time complexity for larger arrays. The bitwise operation `(j - i + 1) & 1` efficiently checks if a number is odd by examining its least significant bit.
