Bulls and Cows - Problem
Bulls and Cows is a classic number guessing game that tests your logical deduction skills! ๐ŸŽฏ

You're playing with a friend who has written down a secret number. Your job is to analyze their guess and provide a helpful hint in the form "xAyB" where:

โ€ข Bulls (A): Digits that are correct and in the right position ๐ŸŽฏ
โ€ข Cows (B): Digits that exist in the secret but are in the wrong position ๐Ÿ„

For example, if the secret is "1807" and the guess is "7810":
โ€ข The '8' is in position 1 in both โ†’ 1 bull
โ€ข The '1' and '7' exist but in wrong positions โ†’ 2 cows
โ€ข Result: "1A2B"

Challenge: Both numbers may contain duplicate digits, making the counting logic tricky!

Input & Output

example_1.py โ€” Basic Case
$ Input: secret = "1807", guess = "7810"
โ€บ Output: "1A3B"
๐Ÿ’ก Note: Position 1 has matching '8' (1 bull). Digits 1, 7, 0 exist in both but wrong positions (3 cows).
example_2.py โ€” No Matches
$ Input: secret = "1123", guess = "0111"
โ€บ Output: "1A1B"
๐Ÿ’ก Note: Position 1 has matching '1' (1 bull). One additional '1' from guess matches with secret (1 cow).
example_3.py โ€” All Bulls
$ Input: secret = "1234", guess = "1234"
โ€บ Output: "4A0B"
๐Ÿ’ก Note: All digits match in correct positions (4 bulls, 0 cows).

Visualization

Tap to expand
๐ŸŽฏ Bulls and Cows Game VisualizationDetective's Evidence Board๐Ÿ” Secret Evidence:1807๐Ÿ”Ž Found Evidence:7810๐ŸŽฏ Analysis Results:BULLS (Perfect Matches)Position 1: Evidence '8' matches exactlyCount: 1 ๐ŸŽฏCOWS (Wrong Location Matches)Evidence '1', '0', '7' found but wrong locationsCount: 3 ๐Ÿ„๐Ÿ“Š Final Report: "1A3B"
Understanding the Visualization
1
Compare Positions
Check each position for exact matches (bulls)
2
Track Frequencies
Count how many times each digit appears
3
Find Wrong-Position Matches
Digits that exist in both but wrong positions (cows)
4
Calculate Final Score
Format as xAyB where x=bulls, y=cows
Key Takeaway
๐ŸŽฏ Key Insight: Use frequency differences to detect matches efficiently - when secret has excess digits, they're available for cows; when guess has excess, they're waiting for matches!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through both strings, checking each position once

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only uses a fixed-size array of 10 integers for digit frequencies

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค secret.length, guess.length โ‰ค 1000
  • secret.length == guess.length
  • secret and guess consist of digits only
Asked in
Google 23 Amazon 18 Apple 15 Microsoft 12
82.3K Views
Medium Frequency
~15 min Avg. Time
1.8K 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