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 <= 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 exatly one pair ofi, jthat0 <= i, j <= n - 1andgrid[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 ngrid into a 1D array of sizen^2. - Frequency Count:
- Use a frequency array or map to count occurrences of numbers from
1ton^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.