Array
Subarray
Sum
Algorithm
Problem Solving

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.

Practice algorithms

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 O(n2)O(n^2) 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 O(n)O(n).

Explanation

  1. Cumulative Sum: Maintain a running sum of the elements. For an index i, the cumulative sum cum_sum[i] is the sum from the start to index i.
  2. 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 to k ends at index i.
  3. Algorithm Steps:
    • Initialize cum_sum as 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 = 1
  • hashMap = \{0: 1, 1: 1\}
  • cumulative_sum = 2
  • (2 - 2) = 0 is in hashMap, increment count by 1.
  • hashMap = \{0: 1, 1: 1, 2: 1\}
  • cumulative_sum = 3
  • (3 - 2) = 1 is in hashMap, 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
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

All Rights Reserved.