Magicsheet logo

Rings and Rods

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Rings and Rods

What is this problem about?

The Rings and Rods interview question gives you a string describing colored rings placed on numbered rods. Each pair of characters in the string represents a color (R, G, or B) and a rod number (09). You must count how many rods have all three colors (R, G, and B) placed on them. This is a hash table-based tracking problem requiring per-rod color set management.

Why is this asked in interviews?

Google asks this problem as a beginner-level hash table and string parsing exercise. It validates that candidates can parse fixed-format strings (two characters at a time), associate attributes with keys (rod numbers), and check set membership conditions. These skills apply to event parsing, log processing, and configuration management systems.

Algorithmic pattern used

The pattern is hash table with set tracking. Use a dictionary mapping rod numbers (0–9) to a set of colors placed on that rod. Parse the input string two characters at a time: color = s[i], rod = int(s[i+1]). Add the color to rod_colors[rod]. After processing all pairs, count how many rods have a set of size 3 (all three colors: R, G, B).

Alternatively, use a bitmask per rod: R=1, G=2, B=4. OR in the bit for each color. Count rods where the bitmask equals 7 (1+2+4).

Example explanation

Input: "B0R0G0R2B2"

  • 'B',0: rod 0 → {B}
  • 'R',0: rod 0 → {B,R}
  • 'G',0: rod 0 → {B,R,G} (size 3!)
  • 'R',2: rod 2 → {R}
  • 'B',2: rod 2 → {R,B}

Rod 0 has all 3 colors. Rod 2 has only 2. Answer: 1.

Bitmask version: rod 0 → B(4)|R(1)|G(2) = 7. Rod 2 → R(1)|B(4) = 5. Count rods with mask == 7: 1.

Common mistakes candidates make

  • Parsing characters one at a time instead of two at a time — each ring is described by exactly two characters.
  • Checking if a set has exactly 3 elements instead of checking if it contains all of {'R','G','B'}.
  • Not initializing the dictionary for each rod — use defaultdict(set) or setdefault.
  • Forgetting that rod numbers go from 0 to 9, but only rods that appear in the input matter.

Interview preparation tip

For the Rings and Rods coding problem, the hash table and string interview pattern is the straightforward approach. The bitmask alternative is elegant and worth mentioning: R=bit 0, G=bit 1, B=bit 2. A rod with all three colors has mask value 7. Google interviewers appreciate candidates who offer the bitmask as an optimization that reduces the per-rod storage from a set to a single integer.

Similar Questions