⚡Flashcard Drill➔
NeetCode #112LC-974MediumArrays & Hashing
← Back to All Problems

#112 · #974 · Subarray Sums Divisible by K(和可被 K 整除的子数组)

📌 Problem Statement & Constraints

Given an integer array nums and an integer k, return the number of non-empty subarrays whose sum is divisible by k. Constraints: 1 <= nums.length <= 2 * 10^4, -10^4 <= nums[i] <= 10^4, 2 <= k <= 10^4.

💡 Core Algorithmic Approaches

  1. A subarray sum nums[i..j] is divisible by k exactly when the two prefix sums P[j+1] and P[i] are congruent modulo k.
  2. So count, for each residue, how many earlier prefixes shared it. Each such pair contributes one valid subarray.
  3. Maintain a hash map from residue to count, seeded with {0: 1} to represent the empty prefix.
  4. Python's % always returns a non-negative result for a positive modulus, which conveniently normalises negative prefix sums.

💻 Benchmark Python3 Implementation

class Solution:
    def subarraysDivByK(self, nums: List[int], k: int) -> int:
        from collections import defaultdict
        cnt = defaultdict(int)
        cnt[0] = 1                         # the empty prefix has residue 0
        cur = 0
        res = 0
        for x in nums:
            cur = (cur + x) % k            # Python's % is non-negative for k > 0
            res += cnt[cur]                # pair with every earlier equal residue
            cnt[cur] += 1
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass with O(1) average hash operations.
💾 Space Complexity
O(min(n, k)) for the residue counts.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting cnt[0] = 1: subarrays starting at index 0 would be missed.
  • Worrying about negative residues: in Python -7 % 5 == 3, so the residues are already normalised. In C++/Java you would need ((cur % k) + k) % k.
  • Using a sliding window: it fails because the values may be negative, so the prefix sums are not monotone.
  • Storing a set of residues rather than counts: two different start indices with the same residue each yield a distinct subarray, so multiplicities matter.
⚡
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 ≤ 3 × 10^4;-10^4 ≤ nums[i] ≤ 10^4;2 ≤ k ≤ 10^4。

核心要点

  • 前缀和取模(标准解) :子数组 nums[j..i] 的和可被 k 整除,等价于 prefix[i] - prefix[j] ≡ 0 (mod k) ,即两个前缀和对 k 取模后 余数相同 。
  • 哈希表计数 :遍历数组维护当前前缀和余数,用字典记录每个余数出现过的次数。每到一个位置,答案加上「与当前余数相同的此前前缀数」。
  • 为什么必须用计数而非集合 :同一余数可能出现多次,每次对应一个不同的起点 j,因此需要统计次数。
  • 初始条件 0: 1 :表示空前缀(余数 0),用于处理「子数组从下标 0 开始」的情况。

常见陷阱

  • 漏掉 cnt[0] = 1 :会丢失所有「从下标 0 开始且和可被 k 整除」的子数组。
  • 先 cnt[prefix] += 1 再 ans += cnt[prefix] :顺序颠倒会把自己这一次也算进去,多计一个空子数组。必须先查询、后记录。
  • 担心 Python 负数取模 :Python 的 % 对负数返回非负结果(如 -3 % 5 == 2 ),因此 prefix 始终在 [0, k) 内,无需额外修正;但在 C++/Java 中必须写成 ((prefix % k) + k) % k 。
  • 与 560 题混淆 :560 题(和为 K 的子数组)的哈希键是 前缀和本身 ;本题的键是 前缀和的余数 。

参考实现

from collections import defaultdict

class Solution:
    def subarraysDivByK(self, nums: list[int], k: int) -> int:
        # cnt[r] = 前缀和对 k 取模余数为 r 的出现次数
        cnt = defaultdict(int)
        cnt[0] = 1                  # 空前缀,余数为 0
        prefix = 0
        ans = 0
        for x in nums:
            prefix = (prefix + x) % k
            ans += cnt[prefix]      # 与之前同余数的每个前缀都构成一个合法子数组
            cnt[prefix] += 1
        return ans