Problem Description
You are given a string representing rings placed on ten rods (labeled 0-9). Each ring is specified as a two-character pair where the first character is the color ('R', 'G', or 'B') and the second is the rod number. The task is to determine how many rods have rings of all three colors.
Key Insights
- Use a hash table (dictionary) to map each rod to the set of colors that appear on it.
- Iterate over the string in steps of two to process each ring's color and rod number.
- Count a rod only if its corresponding set contains all three colors.
Space and Time Complexity
Time Complexity: O(n), where n is the number of rings (processing each pair once).
Space Complexity: O(1), since there are only 10 rods and at most 3 colors per rod.
Solution
We can solve the problem by iterating over the given rings string two characters at a time. For each ring, insert the ring's color into a set associated with the rod number in a dictionary. After processing all rings, count how many rods have a set size of exactly 3 (indicating all colors are present). This approach leverages a hash table (dictionary) and the properties of sets to avoid duplicates, making it efficient and straightforward.