<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 final {
private:
    template<class C>
    using Key = C::key_type;

    template<class C>
    using Mapped = C::mapped_type;

    template<class C>
    static constexpr Mapped<C> getOrDefault(
        const C &container,
        const Key<C> &key,
        const Mapped<C> &mapped
    ) noexcept {
        if (const auto iter{container.find(key)}; iter != container.cend())
            return iter->second;
        return mapped;
    }

    static inline void deleteElement(
        unordered_map<int, size_t> &countMap,
        const int key
    ) noexcept {
        const auto iter{countMap.find(key)};
        --iter->second;
        if (iter->second == 0)
            countMap.erase(iter);
    }

public:
    inline int subarraySum(
        vector<int> &nums,
        const int k
    ) const noexcept {
        const auto length{size(nums)};
        unordered_map<int, size_t> numMap{{nums[0], 1}};
        for (auto i{1UZ}; i < length; ++i) {
            nums[i] += nums[i - 1];
            ++numMap[nums[i]];
        }

        auto result{getOrDefault(numMap, k, 0)};
        for (const auto num : nums) {
            deleteElement(numMap, num);
            result += getOrDefault(numMap, num + k, 0);
        }
        return int(result);
    }
};

46578