subarray sum
array algorithms
sum K
input array
programming challenges

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.

Practice algorithms

Introduction

Finding all subarrays within an array that sum to a specified value KK 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 KK.

  1. Traverse the array: Use two nested loops, the outer loop starts from index 0 to n-1, and the inner loop starts from index of the outer loop to n-1.
  2. 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.
  3. Check condition: If the current sum equals KK, store the subarray.

Complexity

Time Complexity: O(n2)O(n^2) - Since we need to check n(n+1)/2n(n+1)/2 subarrays at most. • Space Complexity: O(1)O(1) - 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.

  1. Initialize: Start with a sum and a hash map to store cumulative sums.
  2. Single iteration: Traverse the array while maintaining the current cumulative sum.
  3. Check hash map: • If sum - K exists in the hash map, it means there is a subarray that ends at the current index and its sum is K. • Update the hash map with the current cumulative sum.
  4. Store subarrays: Whenever a matching subarray is found, store the start and end indices for future reference.

Complexity

Time Complexity: O(n)O(n) - Each element is processed once. • Space Complexity: O(n)O(n) - 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:

IndexElementCumulative Sum (CS)CS-KHash Map (CS as key, frequency as value)Subarrays Found
0101020{0: 1, 10: 1}-
121222{0: 1, 10: 1, 12: 1}-
2-21020{0: 1, 10: 2, 12: 1}-
3-20-100{0: 1, 10: 2, 12: 1, -10: 1}[10, 2, -2, -20]
410010{0: 2, 10: 2, 12: 1, -10: 1}[2, -2, -20, 10]

Additional Details

Edge Cases

  1. All Zeroes: If the array contains all zeroes, for K=0K = 0, every subarray will be valid.
  2. Negative Numbers: The solution should correctly handle negative numbers in a single pass, making this problem more robust against varied input.
  3. Empty Array: An array with no elements should return an empty result.

Applications

  1. Data Analysis: Identifying trends in sequences of numerical data.
  2. Finance: Detecting specific transactional patterns in a series of logs.
  3. Genomics: Finding subsequences of interest in genetic data arrays.

Conclusion

The problem of finding subarrays with a given sum KK 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms