Skip to main content
Back to problems
#2965
Easy Algorithms

Find missing and repeated values

Array Hash Table Math Matrix
83.2% acceptance
Feb 25, 2026
996
49
You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. Each integer appears exactly once except a which appears twice and b which is missing. Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_missing_and_repeated_values(grid: Vec<Vec<i32>>) -> Vec<i32> {
    let n = grid.len();
    let nn = n * n;
    let mut freq = vec![0i32; nn + 1];
    for row in &grid {
      for &v in row {
        freq[v as usize] += 1;
      }
    }
    let mut repeated = 0i32;
    let mut missing = 0i32;
    for v in 1..=nn {
      if freq[v] == 2 { repeated = v as i32; }
      if freq[v] == 0 { missing = v as i32; }
    }
    vec![repeated, missing]
  }
}