Find Missing and Repeated Values

easy math matrix hash table

Problem

You are given an n × n grid whose values come from the range [1, n²]. Every number appears exactly once except one value a that appears twice and one value b that is missing. Return [a, b] — the repeated number and the missing number.

Inputgrid = [[1,3],[2,2]]
Output[2, 4]
Here n = 2, so values run 1..4. Number 2 appears twice and number 4 never appears, so the answer is [2, 4].

def findMissingAndRepeatedValues(grid):
    n = len(grid)
    count = [0] * (n * n + 1)        # count[v] = how often v appears
    for row in grid:                 # tally every cell of the grid
        for v in row:
            count[v] += 1
    a = b = -1
    for v in range(1, n * n + 1):    # scan all candidate values
        if count[v] == 2:
            a = v                    # appears twice -> repeated
        elif count[v] == 0:
            b = v                    # never appears -> missing
    return [a, b]
function findMissingAndRepeatedValues(grid) {
  const n = grid.length;
  const count = new Array(n * n + 1).fill(0); // count[v] = frequency
  for (const row of grid)                     // tally every cell
    for (const v of row) count[v]++;
  let a = -1, b = -1;
  for (let v = 1; v <= n * n; v++) {          // scan candidates
    if (count[v] === 2) a = v;                // repeated value
    else if (count[v] === 0) b = v;           // missing value
  }
  return [a, b];
}
int[] findMissingAndRepeatedValues(int[][] grid) {
    int n = grid.length;
    int[] count = new int[n * n + 1];   // count[v] = frequency
    for (int[] row : grid)              // tally every cell
        for (int v : row) count[v]++;
    int a = -1, b = -1;
    for (int v = 1; v <= n * n; v++) {  // scan candidates
        if (count[v] == 2) a = v;       // repeated value
        else if (count[v] == 0) b = v;  // missing value
    }
    return new int[]{a, b};
}
vector<int> findMissingAndRepeatedValues(vector<vector<int>>& grid) {
    int n = grid.size();
    vector<int> count(n * n + 1, 0);   // count[v] = frequency
    for (auto& row : grid)            // tally every cell
        for (int v : row) count[v]++;
    int a = -1, b = -1;
    for (int v = 1; v <= n * n; v++) { // scan candidates
        if (count[v] == 2) a = v;      // repeated value
        else if (count[v] == 0) b = v; // missing value
    }
    return {a, b};
}
Time: O(n²) Space: O(n²)