def getHint(self, secret, guess):
bulls = sum(map(operator.eq, secret, guess))
both = sum(min(secret.count(x), guess.count(x)) for x in '0123456789')
return '%dA%dB' % (bulls, both  bulls)
3 lines in Python

Hi, Stefan, cool
both
! I try to rewrite it in C++ and I only come up withmultiset
. Do you have some nicer ways?class Solution { public: string getHint(string secret, string guess) { int bull = 0, both = 0, n = secret.length(); for (int i = 0; i < n; i++) bull += (secret[i] == guess[i]); multiset<char> s(secret.begin(), secret.end()), g(guess.begin(), guess.end()); for (char c = '0'; c <= '9'; c++) both += min(s.count(c), g.count(c)); return to_string(bull) + "A" + to_string(both  bull) + "B"; } };

@jianchao.li.fighter Haha, my
both
is the part I don't like. It's still O(n), but 10 passes over each string isn't exactly nice. It's just short and simple.For C++ I don't really have nicer ways than multiset, although
for (char c = '0'; c <= '9'; c++) both += min(count(begin(secret), end(secret), c), count(begin(guess), end(guess), c));
is 23 times faster than yours and a bit shorter.

there is no need to use min.
def getHint(self, secret, guess): bulls = 0 bucket = [0]*10 for s, g in zip(secret, guess): if s == g: bulls += 1 else: bucket[int(s)] += 1 bucket[int(g)] = 1 return '%sA%sB' % (bulls, len(secret)  bulls  sum(cnt for cnt in bucket if cnt>0))
let c = len(secret)  bulls
diff = sum(cnt for cnt in bucket if cnt>0)
0 == sum(bucket)
it can be easily verified that, in two counter solution
let x denote sum of max, cows be sum of min, then
x + cows = 2*c
x  cows = 2*diff
thus cows = c  diff
remove of bulls is not necessary, similar conclusion holds

Elegant solution. Not like mine:
string getHint(string secret, string guess) { int A=0,B=0; int n = secret.size(); vector<bool> vis(n); for (int i = 0; i < n; ++i) { if (guess[i] == secret[i]) { A++; if (vis[i]) { B; for (int j = 0; j < n; ++j) { if (j==i)continue; if (!vis[j] && guess[i] == secret[j]) { B++; vis[j]=true; break; } } } else vis[i]=true; } else { for (int j = 0; j < n; ++j) { if (j==i)continue; if (!vis[j] && guess[i] == secret[j]) { B++; vis[j]=true; break; } } } } return to_string(A)+"A"+to_string(B)+"B"; }
but mine is easier to come up with.