Problem Description
You are given an integer limit and a 2D array queries where each query is of the form [x, y]. There are limit+1 balls, labeled from 0 to limit, and initially, all balls are uncolored. For every query, you color ball x with color y and then determine the number of distinct colors present among all balls (ignoring balls that remain uncolored). Return an array result of length equal to the number of queries, where result[i] denotes the number of distinct colors after the i-th query.
Key Insights
- Use a dictionary (or hash map) to track the current color for each ball.
- Use another dictionary (or hash map) to count the frequency of each color that is actively used.
- When updating the color of a ball, decrement the frequency of the old color, and if its count reaches zero, remove it.
- Increment the frequency of the new color and record the current number of distinct colors.
Space and Time Complexity
Time Complexity: O(n) on average, where n is the number of queries, since each query performs O(1) operations. Space Complexity: O(n) in the worst case for storing the ball-to-color mapping and the color frequency counts.
Solution
The solution primarily uses two hash maps (dictionaries): one to store the current color of each ball and another to store the frequency of each color that has been applied. For every query:
- Check if the ball already has a color. If yes, decrement the count for that color and remove it if the count becomes zero.
- Update the ball’s color with the new color and increment the frequency for the new color.
- After processing the query, the number of keys in the frequency map gives the number of distinct colors currently in use. This approach ensures that each query is processed in O(1) average time.