The Find the Number of Distinct Colors Among the Balls coding problem asks you to simulate coloring a series of balls. You are given a sequence of queries, where each query [ballIndex, color] tells you to paint a specific ball with a new color. If the ball was already colored, its previous color is replaced. After each query, you need to return the total number of distinct colors currently present across all colored balls.
Google and Amazon ask this to test your ability to maintain multiple state dependencies in real-time. It evaluation your proficiency with Hash Table design patterns. Specifically, you need to track which ball has which color and how many balls share each color. This ensures that when a color is replaced, you know if that color has completely disappeared from the set of balls.
This problem uses Frequency Counting with two Hash Tables.
ballToColor: A map from ballIndex to its current color.colorCount: A map from color to the number of balls that currently have that color.[ball, newColor]:
ball was already in ballToColor:
oldColor in colorCount.colorCount[oldColor] becomes 0, remove the color from the map.ballToColor[ball] to newColor.newColor in colorCount.colorCount map.Query 1: [1, 10] (Ball 1 gets color 10). ballToColor: {1: 10}, colorCount: {10: 1}. Distinct colors = 1.
Query 2: [2, 10] (Ball 2 gets color 10). ballToColor: {1: 10, 2: 10}, colorCount: {10: 2}. Distinct colors = 1.
Query 3: [1, 20] (Ball 1 changes to color 20).
Whenever you need to track "Distinct elements in a dynamic set," you usually need two pieces of information: the current mapping and a frequency count of the values. This allows you to update the set's diversity in time.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Replace Elements in an Array | Medium | Solve | |
| Walking Robot Simulation | Medium | Solve | |
| Task Scheduler II | Medium | Solve | |
| Equal Row and Column Pairs | Medium | Solve | |
| Find Latest Group of Size M | Medium | Solve |