2965. Find Missing and Repeated Values
Description
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. The task is to find the repeating and missing numbers a and b.
Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.
Example 1:
Input: grid = [[1,3],[2,2]] Output: [2,4] Explanation: Number 2 is repeated and number 4 is missing so the answer is [2,4].
Example 2:
Input: grid = [[9,1,7],[8,9,2],[3,4,6]] Output: [9,5] Explanation: Number 9 is repeated and number 5 is missing so the answer is [9,5].
Constraints:
2 <= n == grid.length == grid[i].length <= 501 <= grid[i][j] <= n * n- For all
xthat1 <= x <= n * nthere is exactly onexthat is not equal to any of the grid members. - For all
xthat1 <= x <= n * nthere is exactly onexthat is equal to exactly two of the grid members. - For all
xthat1 <= x <= n * nexcept two of them there is exactly one pair ofi, jthat0 <= i, j <= n - 1andgrid[i][j] == x.
Solutions
Solution 1: Counting
We create an array \(cnt\) of length \(n^2 + 1\) to count the frequency of each number in the matrix.
Next, we traverse \(i \in [1, n^2]\). If \(cnt[i] = 2\), then \(i\) is the duplicated number, and we set the first element of the answer to \(i\). If \(cnt[i] = 0\), then \(i\) is the missing number, and we set the second element of the answer to \(i\).
The time complexity is \(O(n^2)\), and the space complexity is \(O(n^2)\). Here, \(n\) is the side length of the matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |