You are given a string rings
representing the placement of rings on rods. The string contains the characters ‘R’, ‘G’, ‘B’ (representing the colors of the rings: red, green, and blue) and digits ‘0’ to ‘9’ (representing the rods). Each ring is described by exactly two characters: its color and the rod it is placed on.
For example, the string "B0R0G0R9B9G9"
means there is a blue ring on rod 0, a red ring on rod 0, a green ring on rod 0, a red ring on rod 9, a blue ring on rod 9, and a green ring on rod 9.
Return the number of rods that have all three colors of rings on them.
Input: rings = "B0R0G0R9B9G9"
Output: 2
Explanation:
- Rod 0 has all three colors: red, green, and blue.
- Rod 9 has all three colors: red, green, and blue.
- Thus, there are 2 rods with all three colors of rings.
Input: rings = "B0R0G0R1G0B1"
Output: 1
Explanation:
- Rod 0 has all three colors: red, green, and blue.
- Rod 1 lacks a green ring.
- Thus, there is only 1 rod with all three colors of rings.
def countPoints(rings: str) -> int:
rod_colors = {}
for i in range(0, len(rings), 2):
color = rings[i]
rod = rings[i + 1]
if rod not in rod_colors:
rod_colors[rod] = set()
rod_colors[rod].add(color)
count = 0
for colors in rod_colors.values():
if len(colors) == 3:
count += 1
return count
# Example usage:
assert countPoints("B0R0G0R9B9G9") == 2
assert countPoints("B0R0G0R1G0B1") == 1
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?