2661. First Completely Painted Row or Column #1185
-
Topics: You are given a 0-indexed integer array Go through each index Return the smallest index Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps: Approach
Detailed Steps
Let's implement this solution in PHP: 2661. First Completely Painted Row or Column <?php
/**
* @param Integer[] $arr
* @param Integer[][] $mat
* @return Integer
*/
function firstCompleteIndex($arr, $mat) {
$m = count($mat);
$n = count($mat[0]);
// Step 1: Preprocess the positions of elements in the matrix
$position_map = [];
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
$position_map[$mat[$i][$j]] = [$i, $j];
}
}
// Step 2: Initialize row and column counts
$row_count = array_fill(0, $m, 0); // Frequency of painted cells in each row
$col_count = array_fill(0, $n, 0); // Frequency of painted cells in each column
// Step 3: Traverse arr and update counts
foreach ($arr as $i => $value) {
list($row, $col) = $position_map[$value];
// Increment the row and column counts
$row_count[$row]++;
$col_count[$col]++;
// Step 4: Check if any row or column is fully painted
if ($row_count[$row] == $n || $col_count[$col] == $m) {
return $i;
}
}
// If no row or column is fully painted, return -1 (although the problem guarantees a solution)
return -1;
}
// Example usage:
$arr = [1, 3, 4, 2];
$mat = [[1, 4], [2, 3]];
echo firstCompleteIndex($arr, $mat); // Output: 2
$arr = [2, 8, 7, 4, 1, 3, 5, 6, 9];
$mat = [[3, 2, 5], [1, 4, 6], [8, 7, 9]];
echo firstCompleteIndex($arr, $mat); // Output: 3
?> Explanation:
Time Complexity:
Space Complexity:
This solution should efficiently handle the problem within the given constraints. |
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Approach
Pre-process the positions of elements:
position_map
) that maps each value in the matrix to its(row, col)
position.Frequency Arrays:
arr
array, we will increment the frequency of the respective row and column for each element.Check for Complete Row or Column:
Return the result