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
JavaScript Total subarrays with Sum K
In this problem, we need to find the total number of continuous subarrays within an array that have a sum equal to a given value K using JavaScript.
Understanding the Problem
Given an array of integers and a target sum K, we need to count all possible subarrays whose elements sum up to K. A subarray is a contiguous sequence of elements within an array. For example, if we have array [1, 2, 3, 4, 5] and K = 6, the subarrays with sum 6 are [1, 2, 3] and [2, 4], giving us a count of 2.
Algorithm
Step 1: Create a function subarraysWithSumK that takes an array and target sum K as parameters.
Step 2: Initialize a counter variable to keep track of valid subarrays.
Step 3: Use nested loops - outer loop for starting index, inner loop for ending index of subarray.
Step 4: Calculate sum of current subarray and increment counter if sum equals K.
Step 5: Return the total count.
Method 1: Brute Force Approach
The straightforward approach uses nested loops to check all possible subarrays:
function subarraysWithSumK(arr, K) {
let count = 0;
// Outer loop for starting index
for (let i = 0; i < arr.length; i++) {
let sum = 0;
// Inner loop for ending index
for (let j = i; j < arr.length; j++) {
sum += arr[j];
// Check if current subarray sum equals K
if (sum === K) {
count++;
}
}
}
return count;
}
// Test the function
const arr = [1, 2, 3, 4, 5];
const K = 6;
console.log(`Subarrays with sum ${K}:`, subarraysWithSumK(arr, K));
// Another example
const arr2 = [1, 1, 1];
const K2 = 2;
console.log(`Subarrays with sum ${K2}:`, subarraysWithSumK(arr2, K2));
Subarrays with sum 6: 2 Subarrays with sum 2: 2
Method 2: Optimized Using Hash Map
For better performance, we can use a hash map to store cumulative sums:
function subarraysWithSumKOptimized(arr, K) {
let count = 0;
let cumulativeSum = 0;
let sumFrequency = new Map();
// Initialize with sum 0 appearing once
sumFrequency.set(0, 1);
for (let i = 0; i < arr.length; i++) {
cumulativeSum += arr[i];
// Check if (cumulativeSum - K) exists in map
if (sumFrequency.has(cumulativeSum - K)) {
count += sumFrequency.get(cumulativeSum - K);
}
// Add current cumulative sum to map
sumFrequency.set(cumulativeSum, (sumFrequency.get(cumulativeSum) || 0) + 1);
}
return count;
}
// Test the optimized function
const arr3 = [1, 2, 3, 4, 5];
const K3 = 6;
console.log(`Optimized result for sum ${K3}:`, subarraysWithSumKOptimized(arr3, K3));
Optimized result for sum 6: 2
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Brute Force | O(n²) | O(1) | Small arrays |
| Hash Map | O(n) | O(n) | Large arrays |
Example with Step-by-Step Trace
function traceSubarrays(arr, K) {
let count = 0;
console.log(`Finding subarrays with sum ${K} in [${arr.join(', ')}]`);
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
let subarray = arr.slice(i, j + 1);
if (sum === K) {
count++;
console.log(`Found: [${subarray.join(', ')}] = ${sum}`);
}
}
}
return count;
}
// Trace example
const result = traceSubarrays([1, 2, 3, 4, 5], 6);
console.log(`Total count: ${result}`);
Finding subarrays with sum 6 in [1, 2, 3, 4, 5] Found: [1, 2, 3] = 6 Found: [2, 4] = 6 Total count: 2
Conclusion
We've implemented two approaches to count subarrays with sum K. The brute force method is simple but has O(n²) complexity, while the hash map approach offers O(n) performance for larger datasets. Choose based on your array size and performance requirements.
