560. Subarray Sum Equals K LeetCode Solution

In this guide, you will get 560. Subarray Sum Equals K LeetCode Solution with the best time and space complexity. The solution to Subarray Sum Equals K problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Subarray Sum Equals K solution in C++
  4. Subarray Sum Equals K solution in Java
  5. Subarray Sum Equals K solution in Python
  6. Additional Resources
560. Subarray Sum Equals K LeetCode Solution image

Problem Statement of Subarray Sum Equals K

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.

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

Constraints:

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

560. Subarray Sum Equals K LeetCode Solution in C++

class Solution {
 public:
  int subarraySum(vector<int>& nums, int k) {
    int ans = 0;
    int prefix = 0;
    unordered_map<int, int> count{{0, 1}};  // {prefix sum: count}

    for (const int num : nums) {
      prefix += num;
      const int target = prefix - k;
      if (const auto it = count.find(target); it != count.cend())
        ans += it->second;
      ++count[prefix];
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

560. Subarray Sum Equals K LeetCode Solution in Java

class Solution {
  public int subarraySum(int[] nums, int k) {
    int ans = 0;
    int prefix = 0;
    Map<Integer, Integer> count = new HashMap<>();
    count.put(0, 1);

    for (final int num : nums) {
      prefix += num;
      ans += count.getOrDefault(prefix - k, 0);
      count.merge(prefix, 1, Integer::sum);
    }

    return ans;
  }
}
// code provided by PROGIEZ

560. Subarray Sum Equals K LeetCode Solution in Python

class Solution:
  def subarraySum(self, nums: list[int], k: int) -> int:
    ans = 0
    prefix = 0
    count = collections.Counter({0: 1})

    for num in nums:
      prefix += num
      ans += count[prefix - k]
      count[prefix] += 1

    return ans
# code by PROGIEZ

Additional Resources

See also  86. Partition List LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.