Statement▼
You are playing a number guessing game called “Bulls and Cows” with a friend.
You write down a secret number, and your friend tries to guess it. After each guess, you provide a hint based on the following:
Bulls: The number of digits that are in the correct position in the
guess.Cows: The number of digits that are in both the
secretand theguessbut in different positions. (These are non-bull digits that could become bulls if rearranged.)
Your task is to return a hint for the guess, formatted as “xAyB”, where:
x is the number of bulls.
y is the number of cows.
Note: Both the
secretnumber and theguessmay contain duplicate digits.
Constraints:
1<= secret.length,guess.length<=103 secret.length == guess.lengthsecretandguessconsist of digits only.
Solution
The solution uses a hash table with a single pass approach to determine the number of bulls and cows in the given strings secret and guess. Bulls are defined as the digits in the correct position, while cows are the digits present in both strings but in different positions. The core idea is to maintain a count of unmatched digits using a hash table and compute bulls and cows simultaneously.
Now, let’s walk through the steps of the solution:
We initialize a hash table
dictto keep track of the counts of unmatched digits.We also initialize two variables,
bullsandcows, to count the bulls and cows, respectively.Next, we iterate through each character of the
secretand in each iteration, we retrieve the corresponding character at the same index from theguess. For each pair of characterssfromsecretandgfromguess, we perform the following checks:If the characters
sandgare the same, we increment thebullscounter by1 , as this means there is a digit in the correct position.Otherwise, if the characters are not the same, we check how many cows can be formed:
We add to the
cowscounter based on the count of unmatched digits stored indict. Specifically, we add1 if the count ofsindictis less than0 (indicating thatswas guessed before) and add1 if the count ofgindictis greater than0 (indicating thatgwas part of thesecretpreviously).We then update the counts in
dictby incrementing the count forsand decrementing the count forgto reflect the unmatched digits.
Finally, we return the result formatted as "{bulls}A{cows}B", where
bullsis the count of bulls andcowsis the count of cows.
Let’s look at the following illustration to get a better understanding: