⚡Flashcard Drill➔
NeetCode #111LC-560MediumArrays & HashingNC 250
← Back to All Problems

#111 · #560 · Subarray Sum Equals K(和为 K 的子数组)

📌 Problem Statement & Constraints

Given an array of integers nums and an integer k, return the total number of contiguous subarrays whose sum equals k. Constraints: 1 <= nums.length <= 2 * 10^4, -1000 <= nums[i] <= 1000, -10^7 <= k <= 10^7.

💡 Core Algorithmic Approaches

  1. A sliding window fails because the array may contain negative numbers, so the running sum is not monotonic in the window bounds.
  2. Use prefix sums with a hash map. Let P[i] be the sum of the first i elements. Then sum(nums[i..j]) = P[j+1] - P[i].
  3. The condition P[j+1] - P[i] == k becomes P[i] == P[j+1] - k. So while scanning, count how many earlier prefix sums equal current - k.
  4. The map stores the frequency of each prefix sum, not just its presence, because multiple earlier prefixes may share the same value.
  5. Initialise the map with {0: 1} to represent the empty prefix, which handles subarrays starting at index 0.

💻 Benchmark Python3 Implementation

class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        from collections import defaultdict
        count = defaultdict(int)
        count[0] = 1                 # the empty prefix, sum 0, seen once
        prefix = 0
        res = 0
        for x in nums:
            prefix += x
            # any earlier prefix equal to (prefix - k) closes a valid subarray
            res += count[prefix - k]
            count[prefix] += 1
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass with O(1) average hash operations. The brute-force prefix-sum double loop is O(n^2).
💾 Space Complexity
O(n) for the hash map, which may hold up to n + 1 distinct prefix sums.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting count[0] = 1: subarrays that start at index 0 would be missed entirely.
  • Storing booleans instead of counts: two different start indices can share the same prefix sum, and each yields a distinct subarray.
  • Using a sliding window: it only works when all values are non-negative, which the constraints do not guarantee.
  • Incrementing the prefix count before adding to the result: an element would be allowed to pair with itself, counting empty subarrays when k == 0.
  • Assuming k must be positive: k can be negative, and the same algorithm handles it unchanged.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

和为 K 的子数组

给你一个整数数组 nums 和一个整数 k,请你统计并返回该数组中和为 k 的 子数组 的个数。子数组是数组中元素的连续非空序列。约束:1 ≤ nums.length ≤ 2 × 10^4;-1000 ≤ nums[i] ≤ 1000;-10^7 ≤ k ≤ 10^7。

核心要点

  • 暴力枚举 :枚举所有 (i, j) 子数组并求和,时间 O(n^2) 或 O(n^3),n = 2 × 10^4 时 O(n^2) 已接近超时边界。
  • 前缀和 + 哈希表(标准解) :设 prefix[i] 为 nums[0..i-1] 之和。子数组 nums[j..i-1] 的和为 prefix[i] - prefix[j] ,要求它等于 k,即 prefix[j] = prefix[i] - k 。
  • 核心转换 :遍历 i 时,只需查询「历史上有多少个前缀和恰好等于 prefix[i] - k 」,把它们累加即可。用哈希表记录每个前缀和出现的次数。
  • 为什么必须用计数而非集合 :同一个前缀和值可能出现多次,每次对应一个不同的起点 j,因此需要统计 次数 而不是仅判断存在。
  • 初始条件 0: 1 的作用 :表示空前缀(即子数组从下标 0 开始的情况),若漏掉会丢失所有以 nums[0] 为起点的答案。

常见陷阱

  • 漏掉 count[0] = 1 :这是本题第一大坑。漏掉后所有「从下标 0 开始且和为 k」的子数组都会被漏计。
  • 误用滑动窗口 :本题 nums 含 负数 ,前缀和不是单调递增的,窗口收缩条件不成立,滑动窗口会得到错误答案。只有当数组全为非负数时滑动窗口才可用。
  • 用 set 代替 dict :set 无法记录同一前缀和出现的次数,会漏计。必须用计数哈希表。
  • 先 count[prefix] += 1 再 ans += count[prefix - k] :顺序颠倒时,当 k == 0 会把自己这一次也算进去,多计一个空子数组。必须先查询、后记录。

参考实现

from collections import defaultdict

class Solution:
    def subarraySum(self, nums: list[int], k: int) -> int:
        # count[s] = 前缀和恰好为 s 的出现次数
        count = defaultdict(int)
        count[0] = 1                 # 空前缀,处理「子数组从下标 0 开始」
        prefix = 0
        ans = 0
        for x in nums:
            prefix += x
            # 若存在前缀和 prefix - k,则它到当前位置构成和为 k 的子数组
            ans += count[prefix - k]
            count[prefix] += 1
        return ans