Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 6, 2025 17:34
Show Gist options
  • Save tatsuyax25/7662f5b8011c49e0c30bc6a6fe801258 to your computer and use it in GitHub Desktop.
Save tatsuyax25/7662f5b8011c49e0c30bc6a6fe801258 to your computer and use it in GitHub Desktop.
You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. 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. Re
/**
* @param {number[][]} grid
* @return {number[]}
*/
var findMissingAndRepeatedValues = function(grid) {
const n = grid.length;
const expectedSum = (n * n * (n * n + 1)) / 2;
let actualSum = 0;
const numCounts = {};
let repeating = -1;
// Flatten the matrix and count occurrences of each number
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const num = grid[i][j];
actualSum += num;
if (num in numCounts) {
repeating = num;
} else {
numCounts[num] = 1;
}
}
}
// Calculate the missing number
const missing = expectedSum - (actualSum - repeating);
// Return the result as an array [repeating, missing]
return [repeating, missing];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment