LeetCode 3160: Find the Number of Distinct Colors Among the Balls Solution

Master LeetCode problem 3160 (Find the Number of Distinct Colors Among the Balls), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3160. Find the Number of Distinct Colors Among the Balls

Problem Explanation

Explanation:

To solve this problem, we can use a HashMap to keep track of the colors assigned to each ball. We iterate through the queries, updating the colors of the balls and counting the distinct colors after each query.

  1. Initialize a HashMap to store the colors assigned to each ball.
  2. Initialize a HashSet to keep track of distinct colors.
  3. Iterate through the queries:
    • Update the color of the ball based on the query.
    • Add the color to the HashSet.
    • Update the result array with the size of the HashSet.
  4. Return the result array.

Time Complexity:

  • The time complexity of this solution is O(n) where n is the number of queries.

Space Complexity:

  • The space complexity of this solution is O(n) where n is the number of queries.

Solution Code

import java.util.*;

class Solution {
    public int[] distinctColors(int limit, int[][] queries) {
        Map<Integer, Integer> colors = new HashMap<>();
        Set<Integer> distinctColors = new HashSet<>();
        int[] result = new int[queries.length];

        for (int i = 0; i < queries.length; i++) {
            int ball = queries[i][0];
            int color = queries[i][1];

            if (colors.containsKey(ball)) {
                int prevColor = colors.get(ball);
                distinctColors.remove(prevColor);
            }

            colors.put(ball, color);
            distinctColors.add(color);

            result[i] = distinctColors.size();
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3160 (Find the Number of Distinct Colors Among the Balls)?

This page provides optimized solutions for LeetCode problem 3160 (Find the Number of Distinct Colors Among the Balls) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3160 (Find the Number of Distinct Colors Among the Balls)?

The time complexity for LeetCode 3160 (Find the Number of Distinct Colors Among the Balls) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3160 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3160 in Java, C++, or Python.

Back to LeetCode Solutions