You and a friend play a guessing game. You write down a secret string of digits, secret, and your friend answers with a string of digits of the same length, guess.
A bull is a position where both strings have the same digit. A cow is a guess digit that is not a bull but still appears in the secret, at another position that is not a bull either. Each secret digit can pair with at most one guess digit, so repeated digits only count as many times as both sides can match them.
Return the hint as one string: the bull count, the letter A, the cow count, then the letter B. Two bulls and one cow give "2A1B".
Example 1
Input: secret = "3592", guess = "5392" Output: "2A2B" Why: 9 and 2 are in place; 3 and 5 are swapped
2 more examples and the constraints
Example 2
Input: secret = "4415", guess = "1444" Output: "1A2B" Why: the 4 at index 1 is a bull; a 1 and one more 4 are cows
Example 3
Input: secret = "1234", guess = "5678" Output: "0A0B" Why: no digit appears on both sides
Constraints
- 1 ≤ length of secret = length of guess ≤ 1,000
- Both strings contain only the digits 0 to 9
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Two passes with leftover countsO(n)
- One pass with a balanceO(n)
The idea in one sentence
Side by side
| Approach | Time | Relative work for 1,000 digits | Verdict |
|---|---|---|---|
| Two passes with leftover counts | O(n) | Passes; easiest to explain | |
| One pass with a balance | O(n) | Best; one loop, one array |
n = length of the strings. Both use a fixed 10-slot array.
Edge cases to test
- Every digit a bull. "8080" against "8080" is "4A0B": no digit is left over to be a cow.
- A bull is not also a cow. "2215" against "0222": the 2 at index 1 is a bull, so only one more 2 can be a cow: "1A1B".
- The guess repeats a digit. "1000" against "0111": the secret has one 1 and the guess three, so 1 pairs only once. With 0 that makes "0A2B".
- One digit long. "7" against "7" is "1A0B"; against "3" it is "0A0B".
Common mistakes
- Counting a digit as a cow once for every copy in the guess, not up to the copies in the secret.
- Including bull positions in the leftover counts, so bulls are counted again as cows.
- Returning the counts in the wrong shape, such as "2B2A" or "2A 2B".
How to talk through it
- 1Clarify. Are both strings the same length? Can digits repeat? Is it digits only?
- 2Split the work. Bulls are a position-by-position check. Cows are a counting question about what is left.
- 3Name the counting rule. Each digit pairs min(spare in secret, spare in guess) times.
- 4Code it. Ten counters are enough, so space is O(1). Offer the one-pass balance as the tighter version.
- 5Test out loud. Run a repeated digit that is also a bull, and a guess with more copies than the secret.