2965. Find Missing and Repeated Values #1397
-
Topics: You are given a 0-indexed 2D integer matrix Return a 0-indexed integer array Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to identify the repeating and missing numbers in a given Approach
Let's implement this solution in PHP: 2965. Find Missing and Repeated Values <?php
/**
* @param Integer[][] $grid
* @return Integer[]
*/
function findMissingAndRepeatedValues($grid) {
$sum = 0;
$counts = array();
foreach ($grid as $row) {
foreach ($row as $num) {
$sum += $num;
if (isset($counts[$num])) {
$counts[$num]++;
} else {
$counts[$num] = 1;
}
}
}
$a = 0;
foreach ($counts as $num => $cnt) {
if ($cnt == 2) {
$a = $num;
break;
}
}
$n = count($grid);
$max = $n * $n;
$S = $max * ($max + 1) / 2;
$b = $a + ($S - $sum);
return array($a, $b);
}
// Example Test Cases
$grid1 = [[1,3],[2,2]];
print_r(findMissingAndRepeated($grid1)); // Output: [2, 4]
$grid2 = [[9,1,7],[8,9,2],[3,4,6]];
print_r(findMissingAndRepeated($grid2)); // Output: [9, 5]
?> Explanation:
This approach efficiently combines counting and sum calculations to determine both the repeating and missing numbers in linear time relative to the number of elements in the grid, making it optimal for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to identify the repeating and missing numbers in a given
n x n
matrix where each number in the range[1, n²]
appears exactly once except for one number that appears twice and another that is missing.Approach
a
).m(m+1)/2
.