⚡Flashcard Drill➔
NeetCode #55LC-2965EasyArrays & Hashing
← Back to All Problems

#55 · #2965 · Find Missing and Repeated Values(找出缺失和重复的数字)

📌 Problem Statement & Constraints

You are given an n x n grid where every integer from 1 to n^2 appears exactly once, except that one value is repeated and one is missing. Return [repeated, missing]. Constraints: 2 <= n <= 50.

💡 Core Algorithmic Approaches

  1. A hash set finds the repeated value in one pass.
  2. The missing value then follows from the sum identity: sum(grid) - n^2(n^2+1)/2 = repeated - missing.
  3. So missing = repeated - (sum(grid) - expected_sum).
  4. This avoids needing the sum of squares, and works for any grid shape.

💻 Benchmark Python3 Implementation

class Solution:
    def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
        seen = set()
        repeated = -1
        total = 0
        n2 = len(grid) ** 2
        for row in grid:
            for v in row:
                total += v
                if v in seen:
                    repeated = v           # second sighting
                seen.add(v)
        expected = n2 * (n2 + 1) // 2
        missing = repeated - (total - expected)   # repeated - missing = total - expected
        return [repeated, missing]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n^2): one pass over the grid.
💾 Space Complexity
O(n^2) for the set. A math-only variant (sum and sum of squares) would use O(1) space but risks overflow in fixed-width languages.

⚠️ Interview Pitfalls & Follow-ups

  • Sign error in the missing formula: total - expected == repeated - missing, so missing = repeated - (total - expected). Rearrange carefully.
  • Returning [missing, repeated]: the required order is [repeated, missing].
  • Using the sum-of-squares approach in a language with 32-bit ints: n^2 reaches 2500 and the sum of squares reaches about 5e9, which overflows. Python is safe, but mention the concern.
  • Forgetting that the grid is 2D: flatten it conceptually; the row structure is irrelevant.
⚡
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

中文速览与面试要点

找出缺失和重复的数字

给你一个下标从 0 开始的二维整数矩阵 grid,其大小为 n × n,其中的值在 [1, n²] 范围内。除了某个元素出现两次之外,每个元素都恰好出现一次。请你找出 重复 的数字 a 和 缺失 的数字 b,以 [a, b] 的形式返回。约束:2 ≤ n ≤ 50;grid[i][j] 在 [1, n²] 内。

核心要点

  • 计数数组(标准解) :由于值域恰好是 [1, n²],可直接开长度 n²+1 的计数数组,遍历矩阵统计频次。
  • 收集答案 :频次为 2 的值是重复数字,频次为 0 的值是缺失数字。
  • 数学解法(O(1) 空间) :设实际总和为 S、实际平方和为 Q,理论总和为 S0 = n²(n²+1)/2、理论平方和为 Q0。令 a 为重复值、b 为缺失值,则 a - b = S - S0 、 a² - b² = Q - Q0 ,即 (a-b)(a+b) = Q - Q0 ,联立可解出 a + b = (Q - Q0) / (S - S0) ,进而求出 a 与 b。
  • 取舍 :计数法 O(n²) 空间、实现直观;数学法 O(1) 空间但需要处理大整数与除零边界(本题 S ≠ S0 必然成立,因为 a ≠ b)。

常见陷阱

  • 值域上界算错 :值域是 [1, n²] 而非 [1, n],计数数组必须开 n² + 1 大小。这是最常见的错误。
  • 数学解法忘记用平方和 :只用总和只能得到 a - b ,一个方程解不出两个未知数,必须联立平方和。
  • 数学解法中整数溢出 :在 C++/Java 中 n = 50 时 n² = 2500,平方和约为 5 × 10^9,超出 int 范围,需用 long long。Python 无此问题。
  • 返回顺序写反 :题目要求返回 [重复值, 缺失值] ,顺序不能颠倒。

参考实现

class Solution:
    def findMissingAndRepeatedValues(self, grid: list[list[int]]) -> list[int]:
        n = len(grid)
        total = n * n
        cnt = [0] * (total + 1)
        for row in grid:
            for v in row:
                cnt[v] += 1
        rep = mis = 0
        for v in range(1, total + 1):
            if cnt[v] == 2:
                rep = v
            elif cnt[v] == 0:
                mis = v
        return [rep, mis]

# 数学解法(O(1) 额外空间):
# N = n * n
# S = sum(sum(row) for row in grid)
# Q = sum(v * v for row in grid for v in row)
# S0 = N * (N + 1) // 2
# Q0 = N * (N + 1) * (2 * N + 1) // 6
# diff = S - S0                 # a - b
# summ = (Q - Q0) // diff       # a + b
# a = (diff + summ) // 2
# b = summ - a
# return [a, b]