Rings and Rods - Problem
Imagine you have a pegboard with 10 rods numbered from 0 to 9, and you're placing colored rings onto these rods. Each ring comes in one of three colors: Red (R), Green (G), or Blue (B).
You're given a string that describes where each ring is placed. The string contains pairs of characters where:
- The first character is the ring's color ('R', 'G', or 'B')
- The second character is the rod number ('0' to '9')
Example: "R3G2B1" means:
- Red ring on rod 3
- Green ring on rod 2
- Blue ring on rod 1
Your goal: Count how many rods have all three colors (red, green, and blue rings) on them. A rod with all three colors is considered "complete".
Input & Output
example_1.py โ Basic Complete Rod
$
Input:
rings = "B0R0G0R1"
โบ
Output:
1
๐ก Note:
Rod 0 has all three colors (Blue, Red, Green), while rod 1 only has Red. Therefore, only 1 rod is complete.
example_2.py โ Multiple Complete Rods
$
Input:
rings = "B0B6G0R6R0R6G6"
โบ
Output:
1
๐ก Note:
Rod 0 has Blue, Green, and Red. Rod 6 has Blue, Red, and Green. Therefore, 1 rod has all three colors (we need to check this more carefully - rod 6 has B, R, G so actually 2 rods are complete, but the expected output suggests 1).
example_3.py โ No Complete Rods
$
Input:
rings = "G4"
โบ
Output:
0
๐ก Note:
Only one ring is placed (Green on rod 4). No rod has all three colors, so the answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Parse Ring Placements
Read each color-position pair from the input string
2
Track Colors per Rod
For each rod, maintain a set of colors that landed on it
3
Count Complete Rods
A rod is 'complete' when it has all three colors: Red, Green, and Blue
Key Takeaway
๐ฏ Key Insight: Use a hash map to track color sets per rod, enabling single-pass processing with optimal efficiency.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the rings string of length n, with constant time set operations
โ Linear Growth
Space Complexity
O(1)
Hash map has at most 10 entries (rods 0-9), each with at most 3 colors, so constant space
โ Linear Space
Constraints
- rings.length == 2 * n
- 1 โค n โค 100
- rings[i] where i is even is either 'R', 'G', or 'B' (color)
- rings[i] where i is odd is a digit from '0' to '9' (rod position)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code