Problem
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= n == grid.length == grid[i].length <= 50
1 <= grid[i][j] <= n * n
- For all
x
that1 <= x <= n * n
there is exactly onex
that is not equal to any of the grid members. - For all
x
that1 <= x <= n * n
there is exactly onex
that is equal to exactly two of the grid members. - For all
x
that1 <= x <= n * n
except two of them there is exatly one pair ofi, j
that0 <= i, j <= n - 1
andgrid[i][j] == x
.
Solution
Method 1 - Using frequency map
To solve this problem, we need to identify the number that appears twice (a
) and the number that is missing (b
) in the given n x n
matrix.
Here is how we can do that:
- Flatten the Matrix: We need to work with all numbers in the matrix in a single dimension. Flatten the
n x n
grid into a 1D array of sizen^2
. - Frequency Count:
- Use a frequency array or map to count occurrences of numbers from
1
ton^2
. - The number with a frequency of 2 is the repeating number
a
. - The number with a frequency of 0 is the missing number
b
.
- Use a frequency array or map to count occurrences of numbers from
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
because we process each element of the grid. - 🧺 Space complexity:
O(n^2)
for storing the frequency count.