2965. Find Missing and Repeated Values - Explanation
Description
You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, (n^2)]. 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 thegridmembers. - For all
xthat1 <= x <= n * nthere is exactly onexthat is equal to exactly two of thegridmembers. - For all
xthat1 <= x <= n * nexcept two of them there is exactly one pair ofi,jthat0 <= i, j <= n - 1andgrid[i][j] == x.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Map / Hash Set - Used to count frequencies or track seen values in a single pass through the grid
- Mathematical Formulas for Sums - The optimal solution uses sum and sum of squares formulas to derive the missing and repeated values without extra space
- 2D Array Traversal - The problem requires iterating through all cells in an n x n grid
1. Brute Force
Intuition
The grid contains numbers from 1 to n*n, but one number appears twice (repeated) and one is missing. The simplest approach is to check each number individually by scanning the entire grid for every possible value. For each number from 1 to n*n, we count how many times it appears. If a number appears twice, it is the repeated value. If it appears zero times, it is the missing value.
Algorithm
- For each number from
1ton*n:- Count its occurrences by scanning every cell in the grid.
- If the count equals
2, this is the repeated number. - If the count equals
0, this is the missing number.
- Return the repeated and missing numbers as the result.
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
n = len(grid)
double = missing = 0
for num in range(1, n * n + 1):
cnt = 0
for i in range(n):
for j in range(n):
if num == grid[i][j]:
cnt += 1
if cnt == 2:
double = num
elif cnt == 0:
missing = num
return [double, missing]Time & Space Complexity
- Time complexity:
- Space complexity:
2. Hash Map
Intuition
Instead of rescanning the grid for every number, we can count all occurrences in a single pass using a hash map. First, we iterate through the grid once and record how many times each value appears. Then, we check each number from 1 to n*n in the map: a frequency of 2 indicates the repeated number, and a frequency of 0 indicates the missing number.
Algorithm
- Traverse the entire grid and store the frequency of each number in a hash map.
- Iterate through numbers from
1ton*n:- If the frequency is
0, record it as the missing number. - If the frequency is
2, record it as the repeated number.
- If the frequency is
- Return the repeated and missing numbers.
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
N = len(grid)
count = defaultdict(int)
for i in range(N):
for j in range(N):
count[grid[i][j]] += 1
double = missing = 0
for num in range(1, N * N + 1):
if count[num] == 0:
missing = num
if count[num] == 2:
double = num
return [double, missing]Time & Space Complexity
- Time complexity:
- Space complexity:
3. Hash Set
Intuition
A hash set can detect duplicates efficiently. As we scan the grid, we add each number to a set. If we try to add a number that already exists in the set, we have found the repeated value. After processing the grid, we iterate from 1 to n*n and check which number is not in the set; that is the missing value.
Algorithm
- Initialize an empty hash set.
- Traverse the grid:
- If the current number is already in the set, it is the repeated number.
- Otherwise, add the number to the set.
- Iterate from
1ton*nand find the number not present in the set; this is the missing number. - Return the repeated and missing numbers.
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
N = len(grid)
seen = set()
double = missing = 0
for i in range(N):
for j in range(N):
if grid[i][j] in seen:
double = grid[i][j]
seen.add(grid[i][j])
for num in range(1, N * N + 1):
if num not in seen:
missing = num
break
return [double, missing]Time & Space Complexity
- Time complexity:
- Space complexity:
4. Math
Intuition
We can solve this without extra data structures using mathematical formulas. Let a be the repeated number and b be the missing number. The sum of the grid differs from the expected sum (1 + 2 + ... + n*n) by exactly a - b. Similarly, the sum of squares differs by a^2 - b^2. From these two equations, we can derive a + b (since a^2 - b^2 = (a - b)(a + b)), and then solve for both values.
Algorithm
- Compute the sum and sum of squares of all elements in the grid.
- Calculate the expected sum using the formula:
n*n * (n*n + 1) / 2. - Calculate the expected sum of squares using:
n*n * (n*n + 1) * (2*n*n + 1) / 6. - Let
diff = gridSum - expectedSum, which equalsa - b. - Let
sqDiff = gridSqSum - expectedSqSum, which equalsa^2 - b^2. - Compute
sum = sqDiff / diff, which equalsa + b. - Solve:
a = (sum + diff) / 2andb = sum - a. - Return
[a, b].
class Solution:
def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
N = len(grid)
gridSum = 0
gridSqSum = 0
for i in range(N):
for j in range(N):
gridSum += grid[i][j]
gridSqSum += grid[i][j] * grid[i][j]
totSum = (N * N * (N * N + 1)) // 2
diff = gridSum - totSum # a - b
totSqSum = (N * N * (N * N + 1) * (2 * N * N + 1)) // 6
sqDiff = gridSqSum - totSqSum # (a^2) - (b^2)
sum = sqDiff // diff # a + b
a = (sum + diff) // 2
b = sum - a
return [a, b]Time & Space Complexity
- Time complexity:
- Space complexity:
Common Pitfalls
Confusing Grid Size with Value Range
The grid has dimensions n x n, but values range from 1 to n*n. Using n instead of n*n as the upper bound when checking for missing or repeated values causes you to miss numbers greater than n. Always iterate through 1 to n*n when scanning for the missing and repeated values.
Integer Overflow in Math Approach
When using the mathematical solution with sum of squares, the values can grow very large. For an n x n grid, the sum of squares formula involves n^4 terms, which can overflow 32-bit integers. Use 64-bit integers (long in Java, long long in C++) for intermediate calculations to avoid incorrect results from overflow.
Sign in to join the discussion