<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>

<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
<strong>Output:</strong> 2
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>
	<li><code>-10<sup>7</sup> &lt;= k &lt;= 10<sup>7</sup></code></li>
</ul>

class Solution:
    # brute force. Still time limit exceeded
#     def subarraySum(self, nums: List[int], k: int) -> int:
#         total_number = 0
#         n = len(nums)
#         for start in range(n):
#             for end in range(start,n):
#                 sum_ = 0
#                 for i in range(start, end+1):
#                     sum_ += nums[i]
#                 if sum_ == k:
#                     total_number += 1
#         return total_number
    
    # # optimized brute force. O(n^2) instead of O(n^3). Still time limit exceeded
    # def subarraySum(self, nums: List[int], k: int) -> int:
    #     total_number = 0
    #     n = len(nums)
    #     for start in range(n):
    #         sum_ = 0
    #         for i in range(start, n):
    #             sum_ += nums[i]
    #             if sum_ == k:
    #                 total_number += 1
    #     return total_number
    # O(N), O(N)
    def subarraySum(self, nums: List[int], k: int) -> int:
        # sum_big - sum_sm == k
        # sum_big - k == sum_sm
        # we store previously seen sum_sm
        # for each sum_big, check if sum_big-k==sum_sm is in the hashmap
        total_num = 0

        h = defaultdict(int)
        h[0] = 1  # sum_sm==0 comes one time per default
        s = 0
        for num in nums:
            s += num
            if s-k in h:
                total_num += h[s-k]
            h[s] += 1
        return total_num
    
    

19200