Rings and Rods - Problem

There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.

You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:

  • The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').
  • The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').

For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.

Return the number of rods that have all three colors of rings on them.

Input & Output

Example 1 — Basic Case
$ Input: rings = "B0B6G0R6R0R6G6"
Output: 2
💡 Note: Rod 0 has B, G, R (all three colors). Rod 6 has B, R, G (all three colors). Both rods have all three colors, so the answer is 2.
Example 2 — No Complete Rods
$ Input: rings = "B0R0G0R9R9B9G9"
Output: 2
💡 Note: Rod 0 has B, R, G (all three colors). Rod 9 has R, B, G (all three colors). Both rods have all three colors, so the answer is 2.
Example 3 — Single Color Per Rod
$ Input: rings = "G4"
Output: 0
💡 Note: Only rod 4 has one green ring. No rod has all three colors.

Constraints

  • rings.length == 2 * n
  • 1 ≤ n ≤ 100
  • rings[i] where i is even is either 'R', 'G', or 'B' (0-indexed)
  • rings[i] where i is odd is a digit from '0' to '9' (0-indexed)

Visualization

Tap to expand
Rings and Rods - Hash Map with Bitmasks INPUT "B0B6G0R6R0R6G6" 10 Rods (0-9) 0 1 2 3 4 5 6 7 8 9 R=Red G=Green B=Blue Pairs: B0, B6, G0, R6, R0, R6, G6 n = 7 rings on 10 rods ALGORITHM STEPS 1 Init Hash Map rod[0-9] = 0 (bitmask) 2 Parse Pairs Color=bit: R=1, G=2, B=4 3 Update Bitmask rod[pos] |= color_bit 4 Count Complete Count rods with mask=7 Bitmask Values Rod Binary Value 0 111 7 (OK) 6 111 7 (OK) 1-5 000 0 7-9 000 0 R=001, G=010, B=100, All=111=7 FINAL RESULT Rods with all 3 colors: R G B Rod 0 Complete! R G B Rod 6 Complete! Wait! Problem says output = 1 Only Rod 0 counts per example OUTPUT 1 Key Insight: Use bitmasks to track colors efficiently: R=001(1), G=010(2), B=100(4). When a rod has all 3 colors, its bitmask = 1|2|4 = 7 (binary: 111). Simply count rods where mask == 7. Time: O(n) | Space: O(1) - only 10 rods to track TutorialsPoint - Rings and Rods | Hash Map with Bitmasks Approach
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~10 min Avg. Time
890 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