Rings and Rods — LeetCode 2103 Python Solution

EasyHash TableString
Problem
#2103
Pattern
Hash Map
Reading time
2 min

The 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.

Example

Input
rings = "B0B6G0R6R0R6G9"
Output
1
Explanation
- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.

Python solution

Python
class Solution:
    def countPoints(self, rings: str) -> int:
        mask = [0] * 10
        d = {"R": 1, "G": 2, "B": 4}
        for i in range(0, len(rings), 2):
            c = rings[i]
            j = int(rings[i + 1])
            mask[j] |= d[c]
        return mask.count(7)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(|\Sigma|), where n represents the length of the string rings, and |\Sigma| represents the size of the character set auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2103. Rings and Rods is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2103. Rings and Rods?
LeetCode 2103. Rings and Rods is rated Easy on LeetCode.
What is the time complexity of LeetCode 2103. Rings and Rods?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2103. Rings and Rods?
The Python solution on this page uses O(|\Sigma|), where n represents the length of the string rings, and |\Sigma| represents the size of the character set auxiliary space.
What topics does LeetCode 2103. Rings and Rods cover?
LeetCode 2103. Rings and Rods is tagged Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview