#2103
Rings and Rods
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking each rod multiple times, we can use an array to track the presence of colors for each rod in a single pass through the rings string. This reduces the number of checks needed.
⚙️
Algorithm
3 steps- 1Step 1: Create an array of size 10, where each element is a set to track colors for each rod.
- 2Step 2: Iterate through the rings string, updating the corresponding rod's set with the color of the ring.
- 3Step 3: Count how many rods have all three colors by checking the size of each set.
solution.py12 lines
1# Full working Python code
2rings = 'B0B6G0R6R0R6G9'
3
4def countRodsWithAllColors(rings):
5 color_map = [set() for _ in range(10)]
6 for i in range(0, len(rings), 2):
7 color = rings[i]
8 position = int(rings[i + 1])
9 color_map[position].add(color)
10 return sum(1 for colors in color_map if len(colors) == 3)
11
12print(countRodsWithAllColors(rings))ℹ
Complexity note: The time complexity is O(n) because we traverse the rings string once, and the space complexity is O(n) due to the storage of color sets for each rod.
- 1Using a set to track colors simplifies the checking process.
- 2Iterating through the rings only once is more efficient.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.