2965. Find Missing and Repeated Values

Intuition

We're given a 2D n x n grid filled with values from 1 to n^2. One number is repeated (A) and one number is missing (B).

To find the missing and repeated numbers, we use mathematical formulas for the sum and sum of squares of the first n^2natural numbers.

the sum of the first n natural numbers:

i=1ni=n(n+1)2\sum_{i=1}^{n} i = \frac{n(n+1)}{2}

the sum of squares of the first n natural numbers:

i=1ni2=n(n+1)(2n+1)6\sum_{i=1}^{n} i^2 = \frac{n(n+1)(2n+1)}{6}

Comparing the actual and expected sums helps us form equations to solve for A and B.

Let:

  • A be the repeating number

  • B be the missing number

We know:

  • currentSum = expectedSum - B + A

  • currentSqSum = expectedSqSum - B² + A²

From which:

  • AMinusB = currentSum - expectedSum = A - B

  • ASquaredMinusBSquared = currentSqSum - expectedSqSum = A² - B² = (A - B)(A + B)

So:

  • APlusB = ASquaredMinusBSquared / AMinusB

  • Then solve: A = (APlusB + AMinusB) / 2 B = APlusB - A

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(n2)\text{O}(n^2)

Code

Last updated