You are tasked with solving the following LeetCode problem:
2103. Rings and Rods
There are n
rings and 10
rods numbered from 0
to 9
. You are given a string rings
of length 2n
that describes the rings that are placed onto the rods. The i-th character of rings
is either 'R'
, 'G'
, or 'B'
(representing the colors Red, Green, and Blue), and the (i+1)-th character is a digit from 0
to 9
representing the rod on which the ring is placed.
Return the number of rods that have all three colors of rings on them.
Before we start, let’s clarify the problem with some questions:
n
?
rings
in steps of 2.
import java.util.HashMap;
import java.util.HashSet;
public class Solution {
public int countPoints(String rings) {
HashMap<Integer, HashSet<Character>> rodColors = new HashMap<>();
// Iterate through the rings string two characters at a time
for (int i = 0; i < rings.length(); i += 2) {
char color = rings.charAt(i);
int rod = rings.charAt(i + 1) - '0'; // Convert char to int
rodColors.putIfAbsent(rod, new HashSet<>());
rodColors.get(rod).add(color);
}
int count = 0;
// Count the rods that have all three colors
for (HashSet<Character> colors : rodColors.values()) {
if (colors.contains('R') && colors.contains('G') && colors.contains('B')) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.countPoints("B0R0G0R9R0B0G0")); // Output should be 1
}
}
rings
string, which has (2n) characters, hence the process itself is (O(n)).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?