261. Bulls and Cows
You are scoring one round of a classic number-guessing game. Your function receives two digit strings of equal length: secret, the hidden number you wrote down, and guess, your friend's attempt at it. Return the score as a string in the exact format "xAyB", where:
xis the number of bulls — positions where the guess has the right digit in the right spot.yis the number of cows — guessed digits that do occur in the secret but sit in the wrong position.
Matching is one-to-one: every digit of the secret can vouch for at most one digit of the guess, a digit already spent on a bull can never double as a cow, and repeated digits pair up copy-for-copy. Both strings may contain duplicate digits and may start with zeros.
Example 1:
Input: secret = "1807", guess = "7810"
Output: "1A3B"
Explanation: The 8 sits in the same position in both strings — one bull. The guess's 7, 1 and 0 all exist in the secret but in different spots — three cows.
Example 2:
Input: secret = "1123", guess = "0111"
Output: "1A1B"
Explanation: The second character is a 1 in both strings — one bull. Of the remaining guess digits (0, 1, 1), only one 1 can still be matched against the secret's leftover 1, so exactly one cow. The other guessed 1 has no unmatched partner left.
Constraints:
- 1 ≤ secret.length ≤ 1000
- guess.length == secret.length
- secret and guess consist only of digits '0'-'9'.
Hints:
Bulls are the easy half: one aligned scan comparing position by position. All the subtlety is in cows when digits repeat — secret "11" against guess "10" must score 1A0B, not 1A1B, because the lone matchable 1 was already spent on the bull.
There are only ten possible digit values. Count how often each digit appears in the non-bull positions of the secret and of the guess separately; digit d then contributes min(secretCount[d], guessCount[d]) cows. With a single signed counter per digit you can even collapse everything into one pass.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: secret = "1807", guess = "7810"
Expected output: "1A3B"