# Solution by keeping count of occurrence of the digits in the secret string.

• Solution by keeping count of occurrence of the digits in the secret string.
Algorithm:

1. First count the occurrence of each number in the secret string and save the count in the index of each number.
2. Traverse through the secret string. If the character at index i in guess string matches with the character at index i in secret string, Increase the bull count and reduce the occurrence of the number in the array.
3. If there is a mismatch and the count in the array is greater than 1 . Count it as a cow and reduce the count in the array.
4. For edge case, where the cow is registered before the bull , the count in the array goes in negative. In such cases, decrease the cow count by 1.
5. Time complexity is O(n) where n is the size of the string.

'''

``````string getHint(string secret, string guess) {
int vals[10]={0};
int x = 0 ;
while (x < secret.size()){
vals[secret[x]-'0']+=1;
x++;
}
int bulls=0;
int cows=0;
int i =0 ;
while (i<guess.size()){
if (secret[i]==guess[i]){
bulls++;
vals[guess[i]-'0']--;

// if the registered value is considered as cow before. The count goes in negative.
if (vals[guess[i]-'0']<0){
cows--;
}
}else{
if (vals[guess[i]-'0'] > 0){
cows++;
vals[guess[i]-'0']--;
}
}
i++;
}

string s ;
s.append(to_string(bulls));
s.append("A");
s.append(to_string(cows));
s.append("B");
return s;
}'''``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.