Back to photostream

Subarray Sum Equals K LeetCode Solution

Problem Statement

The Subarray Sum Equals K LeetCode Solution - "Subarray Sum Equals K" states that you are given an array of integers "nums" and an integer 'k', return the total number of continuous subarrays whose sum equals to 'k'.

Example:

 

nums = ,

k=3

2

Explanation:

 

There are two subarrays whose sum is 3:

 

- First from index 0 to 1 i.e. ,

- Second from index 2 to 2 i.e.

 

nums = ,

k=3

2

Explanation:

 

There are two subarrays whose sum is 2:

 

- First from index 0 to 1 i.e. ,

- Second from index 1 to 2 i.e.

 

Approach

Idea:

The main idea is to use a hash map to store the frequency of prefix sums.

 

So, we'll iterate over the array, finding how many subarrays exist whose sum equals k and ends at the current point on each iteration.

 

So, if the value of the prefix sum up to this point is 'prefixSum,' the next step is to determine how many prefix sums exist whose value is (prefixSum - k). It can be found in O(1) by using the hash map, which stores the frequency of prefix sums.

Code

C++ Program of Subarray Sum Equals K:

#include

using namespace std;

int subarraySum(vector &nums, int k)

{

int n = nums.size();

 

www.tutorialcup.com/leetcode-solutions/subarray-sum-equal...

202 views
0 faves
0 comments
Uploaded on January 6, 2022