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

#124 · #523 · Continuous Subarray Sum(连续的子数组和)

📌 Problem Statement & Constraints

Given an integer array nums and an integer k, return true if nums has a good subarray: a contiguous subarray of length at least 2 whose sum is a multiple of k. Constraints: 1 <= nums.length <= 10^5, 0 <= nums[i] <= 10^9, 1 <= k <= 2^31 - 1.

💡 Core Algorithmic Approaches

  1. As with all divisible-subarray problems, the key is prefix sums modulo k: two prefixes with the same residue bound a subarray whose sum is divisible by k.
  2. Because the subarray must have length at least 2, store the earliest index at which each residue appeared and require the gap to be at least 2.
  3. Seed the map with {0: -1} so that a prefix at index 1 can pair with the virtual empty prefix at index -1, giving length 2.
  4. Only the first occurrence of each residue needs to be stored, since it maximises the gap.

💻 Benchmark Python3 Implementation

class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        first = {0: -1}                    # residue -> earliest prefix index
        cur = 0
        for i, x in enumerate(nums):
            cur = (cur + x) % k
            if cur in first:
                if i - first[cur] >= 2:    # length at least 2
                    return True
            else:
                first[cur] = i             # keep only the earliest
        return False

⚡ Complexity Deep Dive

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

⚠️ Interview Pitfalls & Follow-ups

  • Seeding with {0: 0} instead of {0: -1}: the virtual empty prefix sits at index -1, and using 0 would make a single-element subarray satisfy the length check.
  • Overwriting first[cur]: the earliest index must be preserved to maximise the gap.
  • Requiring >= 2 on the element count rather than the index gap: the gap i - first[cur] already equals the subarray length.
  • Forgetting the k = 1 case: every sum is divisible by 1, so any array of length at least 2 returns true; the algorithm handles it without a special case.
⚡
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

中文速览与面试要点

连续的子数组和

给你一个整数数组 nums 和一个整数 k,编写一个函数来判断该数组是否含有同时满足下列条件的连续子数组:① 子数组大小 至少为 2 ;② 子数组元素总和为 k 的倍数。如果存在,返回 true;否则,返回 false。注意:0 始终视为 k 的一个倍数。约束:1 ≤ nums.length ≤ 10^5;0 ≤ nums[i] ≤ 10^9;0 ≤ k ≤ 2^31 − 1。

核心要点

  • 前缀和取模(标准解) :子数组 nums[j..i] 的和是 k 的倍数,等价于 prefix[i] ≡ prefix[j−1] (mod k) 。
  • 哈希表记录「首次出现的下标」 :对每个余数只保留 最早 出现的下标。这样当再次遇到相同余数时,区间长度 i − first[r] 最大,最容易满足「长度 ≥ 2」。
  • 为什么记录首次而非最近 :本题只判断「是否存在长度 ≥ 2 的合法子数组」,保留最早下标能让区间尽可能长,从而尽早满足长度约束。
  • k 为 0 的特殊处理 :若 k == 0,则「是 0 的倍数」意味着子数组和为 0。此时取模运算会除零,需要单独处理——直接找是否存在长度 ≥ 2 且和为 0 的子数组(用前缀和判重)。

常见陷阱

  • 记录「最近出现下标」而非「最早」 :会得到最短区间,容易漏掉「长度 ≥ 2」的判定。必须保留最早出现的下标。
  • 忘记「长度至少为 2」的检查 :题目要求子数组大小 ≥ 2,仅判断「余数重复」是不够的(可能两个相同余数相邻)。
  • 未处理 k == 0 : prefix % 0 会抛 ZeroDivisionError。必须在取模前判断 k 是否为 0。
  • 与 560、974 混淆 :560 的哈希键是前缀和本身、974 的键是余数且统计 次数 、本题的键是余数但记录 最早下标 。三者的区别正是考点。

参考实现

class Solution:
    def checkSubarraySum(self, nums: list[int], k: int) -> bool:
        # first[r] = 前缀和余数为 r 的最早出现下标
        first = {0: -1}                 # 空前缀,余数 0
        prefix = 0
        for i, x in enumerate(nums):
            prefix += x
            r = prefix % k if k else prefix
            if r in first:
                if i - first[r] >= 2:   # 子数组长度至少为 2
                    return True
            else:
                first[r] = i            # 只记录最早一次
        return False