2965. Find Missing and Repeated Values
Last updated
Last updated
public int[] findMissingAndRepeatedValues(int[][] grid) {
long gridSize = grid.length;
long currentSum = 0;
long currentSquaredSum = 0;
// Step 1: Compute current sum and current squared sum from the grid
for (int row = 0; row < gridSize; ++row) {
for (int col = 0; col < gridSize; ++col) {
currentSum += grid[row][col];
currentSquaredSum += (grid[row][col] * grid[row][col]);
}
}
// Step 2: Calculate expected sum and expected squared sum for numbers from 1 to n^2
long totalNumbers = gridSize * gridSize;
long expectedSum = (totalNumbers * (totalNumbers + 1)) / 2;
long expectedSquaredSum = (totalNumbers * (totalNumbers + 1) * (2 * totalNumbers + 1)) / 6;
// Step 3: Derive A - B and A + B
long aMinusB = currentSum - expectedSum;
long aSquaredMinusBSquared = currentSquaredSum - expectedSquaredSum;
long aPlusB = aSquaredMinusBSquared / aMinusB;
// Step 4: Solve equations to get A and B
int repeated = (int) (aMinusB + aPlusB) / 2;
int missing = (int) (aPlusB - repeated);
// Step 5: Return result
return new int[]{repeated, missing};
}