Example:
Input: arr = [1, 2, 3, 2, 1] sum = 3 Output: Number of Subarrays: 3 Explanation: There are 3 subarrays sum up to the target sum of 3: [1, 2] [3] [2, 1]
There are multiple approaches to solving the problem of counting subarrays with a given sum, and here we going to discuss a few of them starting from a brute force approach to more optimized solutions.
Approach 1: Brute Force.
In this brute-force method, we explore all possible subarrays within the given array and calculate the sum of each subarray to identify the count of subarrays that match the desired sum.
Algorithm:
- Use two nested loops to generate all possible subarrays.
- Calculate the sum of each subarray.
- Count the number of subarrays with the given sum.
Python Code:
# Python code to count subarrays for given sum (Brute Force) def count_subarrays(arr, target_sum): count = 0 n = len(arr) for start in range(n): current_sum = 0 for end in range(start, n): current_sum += arr[end] if current_sum == target_sum: count += 1 return count arr = [1, 2, 3, 2, 1] sum = 3 print("Number of Subarrays:", count_subarrays(arr, sum))
Number of Subarrays: 3
- Time Complexity: As we are checking for all possible subarrays using a nested loop the time complexity of this approach is O(n^2) where n is the length of the array.
- Space Complexity: We are not using any extra space in this approach so the space complexity is O(1).
Approach 2: Prefix Sum.
The prefix sum approach optimizes the solution by leveraging cumulative sums and a hash map to efficiently count subarrays with the given sum. It reduces the time complexity significantly compared to the brute-force method.
Algorithm:
- Calculate the cumulative sum of the array elements.
- Maintain a hash map to store the cumulative sums and their frequencies.
- Determine the count of subarrays with the given sum using the hash map.
Python Code:
# Python code to count subarray for given sum using prefix sum def count_subarrays(arr, target_sum): count = 0 prefix_sum = {0: 1} current_sum = 0 for num in arr: current_sum += num if current_sum - target_sum in prefix_sum: count += prefix_sum[current_sum - target_sum] prefix_sum[current_sum] = prefix_sum.get(current_sum, 0) + 1 return count arr = [1, 4, 20, 3, 10, 5] sum = 33 print("Number of Subarrays:", count_subarrays(arr, sum))
Number of Subarrays: 1
- Time Complexity: We are traversing the array once so the time complexity is O(n).
- Space Complexity: We are using the hash map to store cumulative sums so the space complexity is O(n).
Approach 3: Sliding Window Technique.
This is the most optimized approach to count the subarray with a given sum. The sliding window technique optimizes the solution further by using two pointers to maintain a window within the array. It dynamically adjusts the window based on the current sum, minimizing unnecessary calculations and achieving a linear time complexity.
Algorithm:
- Use two pointers, typically named left and right, to represent the window boundaries.
- Initialize left and right to the start of the array.
- Expand the window by moving the right pointer to the right.
- Adjust the window based on the current sum.
- If the current sum exceeds the desired sum or target sum, shrink the window by moving the left pointer to the right.
- Continue this process until the sum becomes less than or equal to the target sum.
- Whenever the current sum matches the desired sum, increment the count to track the subarrays that satisfy the condition.
- Continue sliding the window until the right pointer reaches the end of the array.
Python Code:
# Python code count subarrays using sliding window algorithm def count_subarrays(arr, target_sum): count = 0 current_sum = 0 left = 0 for right in range(len(arr)): current_sum += arr[right] while current_sum > target_sum and left <= right: current_sum -= arr[left] left += 1 if current_sum == target_sum: count += 1 return count arr = [1, 4, 20, 3, 10, 5, 15] sum = 33 print("Number of Subarrays:", count_subarrays(arr, sum))
Output:
Number of Subarrays: 2
- Time Complexity: In this case where the array elements are non-negative or non-zero, this technique achieves a linear time complexity, typically O(n), making it highly efficient for larger datasets.
- Space Complexity: We are not using any extra space in this sliding window approach so space complexity is O(1).
You can learn the Sliding Window Algorithm in more detail from one of our article: Sliding Window Algorithm with Example.
No comments:
Post a Comment