Given an input array find all subarrays with given sum 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 all subarrays within an array that sum to a specified value is a classic problem in computer science that often emerges in algorithm interviews and competitive programming. Solving this problem effectively can be crucial for tasks ranging from simple data analysis to complex computational tasks.
In this article, we explore how to approach this problem, showcase different algorithms for solving it, discuss their complexities, and illustrate them with examples.
Problem Statement
Given an array of integers arr[] of size n and an integer K, the task is to find all subarrays whose elements sum up to K.
Brute Force Solution
Approach
The simplest approach is to generate all possible subarrays of the given array and check each one's sum to see if it equals .
- Traverse the array: Use two nested loops, the outer loop starts from index
0ton-1, and the inner loop starts from index of the outer loop ton-1. - Calculate the sum: Maintain a sum variable initialized to
0. As you increment the inner loop index, add the value at the current index to the sum. - Check condition: If the current sum equals , store the subarray.
Complexity
• Time Complexity: - Since we need to check subarrays at most. • Space Complexity: - Extra space is used only for storing the result.
Example
Consider the array arr[] = [10, 2, -2, -20, 10] and K = -10.
• Subarray [10, 2, -2, -20] sums to -10.
• Subarray [2, -2, -20, 10] sums to -10.
Optimized Solution Using Hash Map
Approach
Utilizing a hash map (dictionary) can significantly optimize this process by storing cumulative sums and leveraging them to quickly identify subarrays with our target sum.
- Initialize: Start with a sum and a hash map to store cumulative sums.
- Single iteration: Traverse the array while maintaining the current cumulative sum.
- Check hash map: • If
sum - Kexists in the hash map, it means there is a subarray that ends at the current index and its sum isK. • Update the hash map with the current cumulative sum. - Store subarrays: Whenever a matching subarray is found, store the start and end indices for future reference.
Complexity
• Time Complexity: - Each element is processed once. • Space Complexity: - For the hash map storing cumulative sums.
Example
For the same array, arr[] = [10, 2, -2, -20, 10] and K = -10, here's a step-by-step breakdown with a hash map:
| Index | Element | Cumulative Sum (CS) | CS-K | Hash Map (CS as key, frequency as value) | Subarrays Found |
| 0 | 10 | 10 | 20 | {0: 1, 10: 1} | - |
| 1 | 2 | 12 | 22 | {0: 1, 10: 1, 12: 1} | - |
| 2 | -2 | 10 | 20 | {0: 1, 10: 2, 12: 1} | - |
| 3 | -20 | -10 | 0 | {0: 1, 10: 2, 12: 1, -10: 1} | [10, 2, -2, -20] |
| 4 | 10 | 0 | 10 | {0: 2, 10: 2, 12: 1, -10: 1} | [2, -2, -20, 10] |
Additional Details
Edge Cases
- All Zeroes: If the array contains all zeroes, for , every subarray will be valid.
- Negative Numbers: The solution should correctly handle negative numbers in a single pass, making this problem more robust against varied input.
- Empty Array: An array with no elements should return an empty result.
Applications
- Data Analysis: Identifying trends in sequences of numerical data.
- Finance: Detecting specific transactional patterns in a series of logs.
- Genomics: Finding subsequences of interest in genetic data arrays.
Conclusion
The problem of finding subarrays with a given sum can be solved via a straightforward approach using nested loops, but can be significantly optimized using a hash map to store cumulative sums. Understanding these algorithms along with their edge cases and performance implications is essential for anyone working in domains requiring efficient data manipulation and analysis.
Related reading
- Given an RGB value what would be the best way to find the closest match in the database?
- Given an unsorted Array find maximum value of Aj - Ai where ji..in On time
- Given n-1n array, find missing number
- Given n and k, return the kth permutation sequence
- Given parallel lists, how can I sort one while permuting rearranging the other in the same way?
- Given that HashMaps in jdk1.6 and above cause problems with multithreading, how should I fix my code
- Given numbers from 1 to 232-1, one is missing. How to find the missing number optimally?
- Given Prime Number N, Compute the Next Prime?

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.