Finding number of subarrays whose sum equals k
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Finding the number of subarrays within an array where the sum equals a specific value, k, is a common problem encountered in algorithmic programming. This challenge is not merely theoretical but has practical implications in areas like data analysis, financial calculations, and even genetic sequence analysis. In this article, we will explore various methods to address this problem, focusing on efficiency and practicality.
Understanding the Problem
Given an integer array nums and an integer k, the goal is to determine the number of contiguous subarrays whose sum equals k. A naive approach would evaluate each possible subarray, calculate its sum, and check against k, but this can be computationally expensive. Thus, more effective strategies are required.
Brute Force Approach
The brute force method involves evaluating all possible subarrays and checking if their sums equal k. While this method is straightforward, it is not efficient for large arrays due to its time complexity.
Example
Consider the array [1, 2, 3, 4, 5] and k = 5:
- Subarray
[2, 3]: Sum is 5. - Subarray
[5]: Sum is 5.
Thus, there are two subarrays with a sum of 5.
Optimized Approach using Hash Maps
To improve efficiency, a hash map can be utilized to store cumulative sums and determine the number of subarrays with a sum of k. This approach reduces the complexity to .
Explanation
- Cumulative Sum: Maintain a running sum of the elements. For an index
i, the cumulative sumcum_sum[i]is the sum from the start to indexi. - Hash Map Utilization: Store each cumulative sum in a hash map, checking if
(cum_sum[i] - k)exists in the map. If it exists, it indicates that a subarray summing tokends at indexi. - Algorithm Steps:
- Initialize
cum_sumas 0 and a hash map with\{0: 1\}to handle edge cases where the subarray starts from the beginning. - Iterate through the array, updating the cumulative sum.
- Check the hash map for
(cum_sum - k). - Update the hash map with the current cumulative sum.
Pseudocode
cumulative_sum = 1hashMap = \{0: 1, 1: 1\}cumulative_sum = 2(2 - 2) = 0is inhashMap, increment count by 1.hashMap = \{0: 1, 1: 1, 2: 1\}cumulative_sum = 3(3 - 2) = 1is inhashMap, increment count by 1.hashMap = \{0: 1, 1: 1, 2: 1, 3: 1\}- Edge Cases: Consider arrays with all elements equal to
k, zeroes in the array, and negative numbers. - Space Optimization: Using prefix sums can slightly reduce space usage but may complicate edge case handling.
Related reading
- Finding out nth fibonacci number for very large 'n
- Finding out the duplicate element in an array
- Finding out the minimum difference between elements in an array
- Finding out whether there exist two identical substrings one next to another
- Finding overlapping data in arrays
- Finding patterns in list
- Finding pairs with product greater than sum
- Finding positions of milestones given their pairwise distances

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.