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:
the sum of squares of the first n natural numbers:
Comparing the actual and expected sums helps us form equations to solve for A and B.
Let:
Abe the repeating numberBbe the missing number
We know:
currentSum = expectedSum - B + AcurrentSqSum = expectedSqSum - B² + A²
From which:
AMinusB = currentSum - expectedSum = A - BASquaredMinusBSquared = currentSqSum - expectedSqSum = A² - B² = (A - B)(A + B)
So:
APlusB = ASquaredMinusBSquared / AMinusBThen solve:
A = (APlusB + AMinusB) / 2B = APlusB - A
Complexity
Code
Last updated