Find the Number of Distinct Colors Among the Balls - Problem
You are given an integer limit and a 2D array queries of size n x 2.
There are limit + 1 balls with distinct labels in the range [0, limit]. Initially, all balls are uncolored.
For every query in queries that is of the form [x, y], you mark ball x with the color y.
After each query, you need to find the number of distinct colors among all the balls.
Return an array result of length n, where result[i] denotes the number of distinct colors after the i-th query.
Note: When answering a query, lack of a color will not be considered as a color.
Input & Output
Example 1 — Basic Coloring
$
Input:
limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]
›
Output:
[1,2,2,2]
💡 Note:
Initially all balls uncolored. Query [1,4]: ball 1→color 4, distinct colors={4}→1. Query [2,5]: ball 2→color 5, distinct colors={4,5}→2. Query [1,3]: ball 1→color 3, distinct colors={3,5}→2. Query [3,4]: ball 3→color 4, distinct colors={3,4,5}→3.
Example 2 — Same Color Multiple Balls
$
Input:
limit = 3, queries = [[0,1],[1,1],[2,1]]
›
Output:
[1,1,1]
💡 Note:
All queries use same color 1. After each query: distinct colors={1}→1.
Example 3 — Recoloring Ball
$
Input:
limit = 2, queries = [[0,1],[0,2],[1,1]]
›
Output:
[1,1,2]
💡 Note:
Query [0,1]: ball 0→color 1, colors={1}→1. Query [0,2]: ball 0→color 2, colors={2}→1. Query [1,1]: ball 1→color 1, colors={1,2}→2.
Constraints
- 1 ≤ limit ≤ 109
- 1 ≤ queries.length ≤ 105
- queries[i].length == 2
- 0 ≤ queries[i][0] ≤ limit
- 1 ≤ queries[i][1] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
limit=4, queries=[[1,4],[2,5],[1,3]]
2
Process
Color balls and track distinct colors
3
Output
Array of distinct color counts: [1,2,2]
Key Takeaway
🎯 Key Insight: Use a hash map to track color counts efficiently, avoiding the need to rescan all balls after each query
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code