Understand what the interviewer is asking for by using test cases and questions about the problem.
"xAyB"
, where x
is the number of bulls and y
is the number of cows.secret
and guess
.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Count the bulls in the first pass and the cows in the second pass using Counter
.
1) Initialize `bulls` and `cows` to 0.
2) Initialize two frequency dictionaries `secret_count` and `guess_count`.
3) First pass: Count the bulls and populate the dictionaries for non-bull characters.
4) Second pass: Count the cows by finding the minimum count of matching characters in `secret_count` and `guess_count`.
5) Return the result as a string in the format `"xAyB"`.
def get_hint(secret, guess):
bulls = 0
cows = 0
# Manually count the frequency of each character in secret and guess
secret_count = {}
guess_count = {}
# First pass to count bulls and populate the dictionaries
for i in range(len(secret)):
if secret[i] == guess[i]:
bulls += 1
else:
# Update the count for the character in secret
if secret[i] in secret_count:
secret_count[secret[i]] += 1
else:
secret_count[secret[i]] = 1
# Update the count for the character in guess
if guess[i] in guess_count:
guess_count[guess[i]] += 1
else:
guess_count[guess[i]] = 1
# Second pass to count cows
for char in guess_count:
if char in secret_count:
cows += min(secret_count[char], guess_count[char])
return f"{bulls}A{cows}B"