-
Couldn't load subscription status.
- Fork 266
Cows and Bulls
kyra-ptn edited this page Aug 30, 2024
·
2 revisions
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Q
- What is the desired outcome?
- To return the hint for a guess in the format
"xAyB", wherexis the number of bulls andyis the number of cows.
- To return the hint for a guess in the format
- What input is provided?
- Two strings,
secretandguess.
- Two strings,
- What is the desired outcome?
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"`.- Miscounting cows by not properly excluding bull positions.
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"