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
Finding desired sum of elements in an array in JavaScript
Finding groups of elements in an array that sum to a desired value is a common programming problem. This involves checking combinations of consecutive elements to match both a target sum and group size.
Problem Statement
Given an array of numbers, we need to find how many consecutive groups of a specific length sum up to a target value. For example:
const arr = [1, 2, 1, 3, 2]; const sum = 3; const num = 2;
We want to find groups of 2 consecutive elements that sum to 3. The groups [1, 2] at positions 0-1 and [1, 2] at positions 2-3 both satisfy this condition.
Solution Using Sliding Window
The most efficient approach uses a sliding window technique to check consecutive subarrays:
const arr = [1, 2, 1, 3, 2];
const sum = 3;
const num = 2;
const findGroups = (arr = [], sum = 1, num = 1) => {
let count = 0;
// Check if we can form groups of required size
if (num > arr.length) {
return 0;
}
// Slide window through array
for (let i = 0; i acc + val, 0);
if (partSum === sum) {
count++;
}
}
return count;
};
console.log(findGroups(arr, sum, num));
2
How It Works
The algorithm examines each possible consecutive group:
- Position 0-1: [1, 2] ? sum = 3 ?
- Position 1-2: [2, 1] ? sum = 3 ?
- Position 2-3: [1, 3] ? sum = 4 ?
- Position 3-4: [3, 2] ? sum = 5 ?
Alternative: More Efficient Approach
For better performance with large arrays, calculate the sum incrementally:
const findGroupsOptimized = (arr = [], targetSum = 1, groupSize = 1) => {
if (groupSize > arr.length) return 0;
let count = 0;
let currentSum = 0;
// Calculate sum of first window
for (let i = 0; i
2
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Sliding Window (Basic) | O(n × k) | O(k) | Small arrays |
| Optimized Sliding Window | O(n) | O(1) | Large arrays |
Conclusion
The sliding window technique efficiently finds consecutive groups with a target sum. The optimized version provides O(n) performance by avoiding repeated sum calculations.
