Bulls and Cows
Problem
Given the secret and the guess (same length, digits only), return "xAyB" where x = bulls (digit and position match) and y = cows (digit in the secret but at a different position).
secret = "1807", guess = "7810""1A3B"def get_hint(secret, guess):
bulls = 0
cs, cg = [0]*10, [0]*10
for a, b in zip(secret, guess):
if a == b: bulls += 1
else:
cs[int(a)] += 1
cg[int(b)] += 1
cows = sum(min(cs[i], cg[i]) for i in range(10))
return f"{bulls}A{cows}B"
function getHint(secret, guess) {
let bulls = 0;
const cs = new Array(10).fill(0), cg = new Array(10).fill(0);
for (let i = 0; i < secret.length; i++) {
if (secret[i] === guess[i]) bulls++;
else {
cs[+secret[i]]++;
cg[+guess[i]]++;
}
}
let cows = 0;
for (let d = 0; d < 10; d++) cows += Math.min(cs[d], cg[d]);
return bulls + "A" + cows + "B";
}
class Solution {
public String getHint(String secret, String guess) {
int bulls = 0;
int[] cs = new int[10], cg = new int[10];
for (int i = 0; i < secret.length(); i++) {
char a = secret.charAt(i), b = guess.charAt(i);
if (a == b) bulls++;
else { cs[a - '0']++; cg[b - '0']++; }
}
int cows = 0;
for (int d = 0; d < 10; d++) cows += Math.min(cs[d], cg[d]);
return bulls + "A" + cows + "B";
}
}
string getHint(string secret, string guess) {
int bulls = 0;
int cs[10] = {0}, cg[10] = {0};
for (int i = 0; i < (int)secret.size(); i++) {
if (secret[i] == guess[i]) bulls++;
else { cs[secret[i]-'0']++; cg[guess[i]-'0']++; }
}
int cows = 0;
for (int d = 0; d < 10; d++) cows += min(cs[d], cg[d]);
return to_string(bulls) + "A" + to_string(cows) + "B";
}
Explanation
A bull is a digit that matches both value and position; a cow is a digit that exists somewhere in the secret but is in the wrong spot. We can find both in a single pass plus a quick tally.
We loop over the positions together. Whenever secret[i] equals guess[i] we increment bulls right away. When they differ, the digits are not bulls but might still be cows, so we record them in two small count arrays of size 10: cs for leftover secret digits and cg for leftover guess digits.
After the loop, a digit can form a cow only as many times as it appears in both leftover piles. So for each digit d from 0 to 9 we add min(cs[d], cg[d]) to cows.
The min is the key: it stops us from over-counting when a digit appears a different number of times on each side.
Example: secret="1807", guess="7810". The 8 at index 1 is a bull. The leftover digits 1, 0, 7 each appear in both piles, so cows = 3, giving "1A3B".