AlgoMaster Logo

Subarray Sum Equals K

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The brute force approach checks every possible subarray and sums the elements to check if it equals k. This approach is simple to implement but can be inefficient for large arrays.

Intuition:

We iterate through each starting point of a subarray and for each starting point, check every possible end point. This gives us every possible subarray.

Code:

2. Prefix Sum Array

We can improve our approach by using a cumulative sum array to keep track of the sum of the elements up to each index.

Intuition:

The cumulative sum array allows us to quickly compute the sum of elements between two indices in constant time by subtracting the cumulative sum of the index before the start of the subarray from the end index.

Code:

3. Prefix Sum + HashMap

This optimized approach leverages a HashMap to track the number of times a particular cumulative sum has appeared.

Intuition:

While iterating through the array, we keep track of the cumulative sum. We use a HashMap to store the frequency of each cumulative sum we have encountered. For each new cumulative sum currentSum, we check if currentSum - k exists in the HashMap. If it does, it means there is a subarray ending at the current index with sum k.

Code: