Given an unsorted array of integers, find the number of subarrays having a sum exactly equal to a given number k.
Answer:-
To solve this problem, we can use a sliding window approach. We start with two pointers, left and right, at the beginning of the array. We keep a running sum of the elements between the left and right pointers. If the sum is less than k, we move the right pointer to the right. If the sum is greater than k, we move the left pointer to the right. If the sum is equal to k, we increment a counter and move both the left and right pointers to the right.
Here is the algorithm:
- Initialize a variable count to 0 and a variable sum to 0.
- Initialize two pointers, left and right, to 0.
- Loop while right < n:
- a. Add arr[right] to sum.
- b. While sum > k, subtract arr[left] from sum and increment left.
- c. If sum == k, increment count and move both left and right pointers to the right.
- d. Increment right.
- Return count.
Here is the Python code:
def count_subarrays(arr, k):
n = len(arr)
count = 0
sum = 0
left = 0
right = 0
while right < n:
sum += arr[right]
while sum > k:
sum -= arr[left]
left += 1
if sum == k:
count += 1
left += 1
right += 1
else:
right += 1
return count
For the input arr[] = {9, 4, 20, 3, 10, 5} and k = 33,
the output will be 2.