You are playing the Bulls and Cows game with your friend. You write down a secret number, and your friend tries to guess it.
The game follows these rules:
Given the secret number and your friend’s guess, return a hint. The hint should be formatted as “xAyB”, where x is the number of bulls and y is the number of cows.
secret and guess simultaneously to count bulls (same position and same digit).secret and guess for cow counting:
secret and guess are different, update the frequency.def getHint(secret: str, guess: str) -> str:
bulls = 0
cows = 0
secret_counts = [0] * 10
guess_counts = [0] * 10
for s, g in zip(secret, guess):
if s == g:
bulls += 1
else:
secret_counts[int(s)] += 1
guess_counts[int(g)] += 1
for i in range(10):
cows += min(secret_counts[i], guess_counts[i])
return f"{bulls}A{cows}B"
n is the length of the input strings secret and guess. We iterate over the strings a constant number of times (a few counts and comparisons).This approach efficiently calculates the number of bulls and cows by leveraging simple counting and iteration, ensuring clarity and performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?