Skip to content

[560] Subarray Sum Equals K

https://leetcode.com/problems/subarray-sum-equals-k/description/

  • algorithms
  • Medium (40.65%)
  • Source Code: 560.subarray-sum-equals-k.py
  • Total Accepted: 93.7K
  • Total Submissions: 223.2K
  • Testcase Example: '[1,1,1]\n2'

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

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

Note:

The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

python
class Solution(object):
    def subarraySum(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if not nums: return 0
        sm = ans = 0
        table = {}
        table[0] = 1
        for n in nums:
            sm += n
            if sm not in table:
                table[sm] = 0
            table[sm] += 1

            if sm-k in table:
                ans += table[sm-k]

        return ans
#
#
# print Solution().subarraySum([1,1,1],2)
#

Last updated: