⬅ Previous Topic
Longest Consecutive Sequence in ArrayNext Topic ⮕
Sort an Array of 0s, 1s, and 2s⬅ Previous Topic
Longest Consecutive Sequence in ArrayNext Topic ⮕
Sort an Array of 0s, 1s, and 2sTopic Contents
Given an integer array arr
and a target sum k
, your task is to find the total number of continuous subarrays whose elements add up to exactly k
.
A subarray is a sequence of elements that appears in the same order in the array and is contiguous. The same element can be included in multiple subarrays if it appears in different positions.
This problem is common in applications involving range-based queries, financial analysis, and interval sum counting.
arr
and a target k
.curr_sum = 0
and a hash map prefix_count
to store frequency of prefix sums.count = 0
.curr_sum
.curr_sum == k
, increment count
by 1.curr_sum - k
exists in prefix_count
, add its frequency to count
.curr_sum
in prefix_count
.count
.from collections import defaultdict
def count_subarrays_with_sum(arr, k):
prefix_count = defaultdict(int)
curr_sum = 0
count = 0
for num in arr:
curr_sum += num
if curr_sum == k:
count += 1
if (curr_sum - k) in prefix_count:
count += prefix_count[curr_sum - k]
prefix_count[curr_sum] += 1
return count
# Sample Input
arr = [1, 1, 1]
k = 2
print("Count of Subarrays:", count_subarrays_with_sum(arr, k))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | Each element is visited exactly once, and all operations (hashmap lookups and updates) take constant time. |
Average Case | O(n) | On average, the algorithm maintains a prefix sum hashmap and performs constant-time operations per element. |
Average Case | O(n) | Even in the worst case, the array is traversed only once and hashmap operations remain O(1), resulting in linear time complexity. |
O(n)
Explanation: A hashmap is used to store the frequency of prefix sums, which can grow up to the size of the input array in the worst case.
⬅ Previous Topic
Longest Consecutive Sequence in ArrayNext Topic ⮕
Sort an Array of 0s, 1s, and 2sYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.