Subarray Sum Equals K Leetcode Solution

Subarray Sum Equals K Leetcode Problem :

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

jump game leetcode

Subarray Sum Equals K Leetcode Solution :

Constraints :

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -107 <= k <= 107

Example 1:

  • Input: nums = [1,2,3], k = 3
  • Output: 2

Approach :

The solution uses a hash table to store the cumulative sum of the array up to each index, along with the number of times that sum has occurred. The algorithm works as follows:

  1. Initialize a hash table map to store the cumulative sum of the array up to each index, along with the number of times that sum has occurred.

  2. Initialize a variable count to store the number of subarrays with sum k.

  3. Iterate over the array, starting at index 0.

  4. Add the current element to the cumulative sum.

  5. If the cumulative sum is equal to k, increment count.

  6. If the cumulative sum minus k is present in the hash table, increment count by the number of times that sum has occurred.

  7. Add the current cumulative sum to the hash table, along with the number of times that sum has occurred.

  8. Return count.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription