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
๐ŸŽฏ Ring Toss Game: Finding Complete RodsGame Setup: 10 numbered rods (0-9)Players throw Red, Green, and Blue ringsGoal: Count rods that caught all three colorsExample: "B0R0G0R1"0Complete! โœ“1IncompleteOther rods (2-9):No rings๐Ÿ† Result: 1 Complete RodRod 0 has all three colors!Algorithm: O(n) time, O(1) space
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

n
2n
โœ“ 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

n
2n
โœ“ 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)
Asked in
Meta 15 Google 12 Amazon 8 Microsoft 5
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen