Solution: Bulls and Cows
Let’s solve the Bulls and Cows problem using the Hash Maps pattern.
We'll cover the following
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
secret
and theguess
but 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
secret
number and theguess
may contain duplicate digits.
Constraints:
secret.length
,guess.length
secret.length == guess.length
secret
andguess
consist 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
dict
to keep track of the counts of unmatched digits.We also initialize two variables,
bulls
andcows
, to count the bulls and cows, respectively.Next, we iterate through each character of the
secret
and in each iteration, we retrieve the corresponding character at the same index from theguess
. For each pair of characterss
fromsecret
andg
fromguess
, we perform the following checks:If the characters
s
andg
are the same, we increment thebulls
counter by, 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
cows
counter based on the count of unmatched digits stored indict
. Specifically, we addif the count of s
indict
is less than(indicating that s
was guessed before) and addif the count of g
indict
is greater than(indicating that g
was part of thesecret
previously).We then update the counts in
dict
by incrementing the count fors
and decrementing the count forg
to reflect the unmatched digits.
Finally, we return the result formatted as "{bulls}A{cows}B", where
bulls
is the count of bulls andcows
is the count of cows.
Let’s look at the following illustration to get a better understanding:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.