Bulls and Cows - Problem

You are playing the Bulls and Cows game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:

Bulls: Digits in the guess that are in the correct position

Cows: Digits in the guess that are in your secret number but are located in the wrong position (specifically, the non-bull digits in the guess that could be rearranged to become bulls)

Given the secret number and your friend's guess, return the hint for your friend's guess.

The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows.

Note: Both secret and guess may contain duplicate digits.

Input & Output

Example 1 — Basic Case
$ Input: secret = "1807", guess = "7810"
Output: 1A3B
💡 Note: Bull: position 1 (8==8). Cows: digit 1 (pos 0→2), digit 0 (pos 2→3), digit 7 (pos 3→0). Total: 1 bull, 3 cows.
Example 2 — No Cows
$ Input: secret = "1123", guess = "0111"
Output: 1A1B
💡 Note: Bull: position 1 (1==1). Cow: one digit 1 from guess matches secret (but secret has 3 ones, guess has 2 after removing bull, so min(2,1)=1 cow).
Example 3 — All Bulls
$ Input: secret = "1234", guess = "1234"
Output: 4A0B
💡 Note: All positions match exactly: 4 bulls, 0 cows.

Constraints

  • 1 ≤ secret.length, guess.length ≤ 1000
  • secret.length == guess.length
  • secret and guess consist of digits only.

Visualization

Tap to expand
Bulls and Cows Game: secret='1807', guess='7810'1807pos 0pos 1pos 2pos 3SECRET7810GUESSBULL: 8==8 ✓COW: 7COW: 1COW: 0Result: 1 Bull + 3 Cows = 1A3B
Understanding the Visualization
1
Input
secret='1807', guess='7810'
2
Process
Compare positions and count digit matches
3
Output
Format as xAyB (1A3B)
Key Takeaway
🎯 Key Insight: Bulls are position matches, cows are digit matches in wrong positions - use frequency counting for efficiency
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen