#2965

Find Missing and Repeated Values

Easy
ArrayHash TableMathMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(n)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution leverages mathematical properties to find the missing and repeated numbers without using extra space for counting. We can use the sum of the first n² natural numbers to find the missing number and the repeated number through a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the expected sum of numbers from 1 to n² using the formula n² * (n² + 1) / 2.
  2. 2Step 2: Calculate the actual sum of numbers in the matrix and identify the repeated number during this process.
  3. 3Step 3: Use the difference between the expected sum and actual sum to find the missing number.
solution.py16 lines
1# Full working Python code
2
3def findMissingAndRepeated(grid):
4    n = len(grid)
5    expected_sum = n * n * (n * n + 1) // 2
6    actual_sum = 0
7    seen = set()
8    repeated = -1
9    for row in grid:
10        for num in row:
11            actual_sum += num
12            if num in seen:
13                repeated = num
14            seen.add(num)
15    missing = expected_sum - (actual_sum - repeated)
16    return [repeated, missing]

Complexity note: The time complexity is O(n²) due to iterating through the n*n matrix, while the space complexity is O(n) for the set used to track seen numbers.

  • 1The problem can be solved using frequency counting or mathematical properties.
  • 2Identifying the repeated number can be done while calculating the sum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.