LeetCode solutions

3434. Find the Number of Distinct Colors Among the Balls

My accepted Python solution to LeetCode problem 3434, Find the Number of Distinct Colors Among the Balls, running in 59ms.

  • Difficulty: Medium
  • Python
  • Runtime 59ms
  • Memory 64.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 59ms, memory 64.1MB, accepted 2026-01-02.

python
class Solution:
    def queryResults(self, limit: int, queries: List[List[int]]) -> List[int]:
        ball_to_color = {}  # ball -> color
        color_count = {}    # color -> count of balls with this color
        
        result = []
        
        for ball, color in queries:
            # If ball already has a color, decrease that color's count
            if ball in ball_to_color:
                old_color = ball_to_color[ball]
                color_count[old_color] -= 1
                if color_count[old_color] == 0:
                    del color_count[old_color]
            
            # Assign new color to ball
            ball_to_color[ball] = color
            color_count[color] = color_count.get(color, 0) + 1
            
            # Count distinct colors
            result.append(len(color_count))
        
        return result

Source