3160. Find the Number of Distinct Colors Among the Balls #1283
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Feb 7, 2025
Replies: 1 comment 2 replies
-
We need to efficiently track the number of distinct colors among balls after each query. Each query updates the color of a specific ball, and we need to determine the number of distinct colors present after each update. Approach
Let's implement this solution in PHP: 3160. Find the Number of Distinct Colors Among the Balls <?php
/**
* @param Integer $limit
* @param Integer[][] $queries
* @return Integer[]
*/
function queryResults($limit, $queries) {
$colorMap = array();
$colorCount = array();
$result = array();
foreach ($queries as $query) {
$x = $query[0];
$y = $query[1];
// Check if the ball was previously colored
if (isset($colorMap[$x])) {
$oldColor = $colorMap[$x];
$colorCount[$oldColor]--;
if ($colorCount[$oldColor] == 0) {
unset($colorCount[$oldColor]);
}
}
// Update the ball's color
$colorMap[$x] = $y;
if (isset($colorCount[$y])) {
$colorCount[$y]++;
} else {
$colorCount[$y] = 1;
}
// Record the current number of distinct colors
$result[] = count($colorCount);
}
return $result;
}
// Example usage:
// Example 1
$limit = 4;
$queries = [[1, 4], [2, 5], [1, 3], [3, 4]];
echo "Output: " . json_encode(queryResults($limit, $queries)) . "\n";
// Example 2
$limit = 4;
$queries = [[0, 1], [1, 2], [2, 2], [3, 4], [4, 5]];
echo "Output: " . json_encode(queryResults($limit, $queries)) . "\n";
?> Explanation:
This approach ensures that each query is processed in constant time, making the solution efficient and scalable for large inputs. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
topugit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We need to efficiently track the number of distinct colors among balls after each query. Each query updates the color of a specific ball, and we need to determine the number of distinct colors present after each update.
Approach
Data Structures: Use two hash maps (associative arrays in PHP):
colorMap
to track the current color of each ball.colorCount
to track the number of balls for each color.Processing Queries:
colorCount
. If the count reaches zero, remove the color fromcolorCount
.colorMap
and increment the count of the new color incolorCount
.