You are playing the “Bulls and Cows” game with your friend.
You write a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The function to be implemented is:
public String getHint(String secret, String guess)
The input strings secret and guess are of equal length and contain only digits.
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation:
[1 bull (8) and 3 cows]
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation:
[1 bull (1) and 1 cow (1)]
secret and guess can contain leading zeros as they are simply strings of digits.secret and guess?
secret and guess will be the same and it’s guaranteed by the problem statement.secret and guess?
secret and guess in parallel and count the number of bulls (i.e., correct digits in the correct position).secret and guess. Then, iterate over these frequency arrays to determine the number of cows.secret and guess.secret and guess to find bulls and fill frequency arrays for the remaining characters.Here’s the implementation in Java:
public class BullsAndCows {
public String getHint(String secret, String guess) {
int bulls = 0;
int[] secretCount = new int[10];
int[] guessCount = new int[10];
for (int i = 0; i < secret.length(); i++) {
char sChar = secret.charAt(i);
char gChar = guess.charAt(i);
if (sChar == gChar) {
bulls++;
} else {
// Increase frequency counts for non-matching characters
secretCount[sChar - '0']++;
guessCount[gChar - '0']++;
}
}
int cows = 0;
// Calculate cows based on the minimum frequency of characters in unmatched characters.
for (int i = 0; i < 10; i++) {
cows += Math.min(secretCount[i], guessCount[i]);
}
return bulls + "A" + cows + "B";
}
public static void main(String[] args) {
BullsAndCows solution = new BullsAndCows();
System.out.println(solution.getHint("1807", "7810")); // Output: "1A3B"
System.out.println(solution.getHint("1123", "0111")); // Output: "1A1B"
}
}
secret (or guess since they are of equal length). We traverse the strings a constant number of times.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?