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 (secret has 2 ones total, after removing bull secret has 1 one remaining, guess has 2 ones remaining, so min(1,2)=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 - Single Pass Optimized INPUT Secret Number 1 8 0 7 Index: 0 1 2 3 Guess Number 7 8 1 0 Index: 0 1 2 3 secret = "1807" guess = "7810" Find Bulls (exact match) and Cows (wrong position) ALGORITHM STEPS 1 Initialize Counters bulls=0, cows=0 count[0-9] array for digits 2 Single Pass Loop For each index i: Compare s[i] with g[i] 3 Count Bulls/Cows If s[i]==g[i]: bulls++ Else: track in count[] 4 Format Result Return "xAyB" string Position Analysis: i=0: s=1, g=7 (diff) cow i=1: s=8, g=8 (same) BULL i=2: s=0, g=1 (diff) cow i=3: s=7, g=0 (diff) cow Bulls: 1, Cows: 3 FINAL RESULT Bulls (Exact Match) 8 Position 1: Both have "8" Cows (Wrong Position) 1 0 7 Present but wrong positions Output: 1A3B Key Insight: Single pass optimization: Use a count array where count[digit]++ for secret digits and count[digit]-- for guess digits. When we see count[s] is negative, we found a cow (s appeared in guess before). Same logic for count[g] being positive. This achieves O(n) time and O(1) space (fixed 10-digit count array) in a single traversal! TutorialsPoint - Bulls and Cows | Single Pass Optimized Approach
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