[LeetCode] Bulls and Cows

299. Bulls and Cows

You are playing the Bulls and Cows game with your friend.

You write down 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 number of “bulls”, which are digits in the guess that are in the correct position.
  • The number of “cows”, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the secret number secret and your friend’s guess guess, return the hint for your friend’s guess.

The hint should be formatted as “xAyB”, where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
string getHint(string secret, string guess) {
int sec[10]{0,},gues[10]{0,},bulls=0,cows=0;
for(int i = 0; i < secret.size(); i++) {
if(secret[i] == guess[i]) bulls++;
else {
sec[secret[i]&0b1111]++;
gues[guess[i]&0b1111]++;
}
}
for(int i = 0; i < 10; i++) {
cows += min(sec[i], gues[i]);
}
return to_string(bulls) + 'A' + to_string(cows) + 'B';
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/bulls-and-cows/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.