Space
Open
From Fieldwork
Scales
Archive
Why this works (The Logic)
The Bulls (A): We iterate through secret and guess simultaneously. If the digits at the same index match, that is an automatic Bull. We do not add these to our counters because they are "consumed."
The Cows (B): This is where the edge cases live.
We take all the digits that weren't Bulls and put them into frequency counters.
The formula for cows is the intersection of the counts.
class Solution:
def getHint(self, secret: str, guess: str) -> str:
bulls = 0
# We will store the characters that are NOT bulls here
secret_leftovers = []
guess_leftovers = []
# Pass 1: Find Bulls and filter out non-matches
for s, g in zip(secret, guess):
if s == g:
bulls += 1
else:
secret_leftovers.append(s)
guess_leftovers.append(g)
# Pass 2: Count Cows using the leftovers
# We count the frequency of digits in both leftover lists
s_counts = Counter(secret_leftovers)
g_counts = Counter(guess_leftovers)
cows = 0
# The number of cows for a specific digit is the minimum
# of its occurrence in secret vs guess.
for digit in s_counts:
cows += min(s_counts[digit], g_counts[digit])
return f"{bulls}A{cows}B"Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode