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
โข 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
โข The
โข The
โข Result:
Challenge: Both numbers may contain duplicate digits, making the counting logic tricky!
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
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
โ Linear Growth
Space Complexity
O(1)
Only uses a fixed-size array of 10 integers for digit frequencies
โ Linear Space
Constraints
- 1 โค secret.length, guess.length โค 1000
- secret.length == guess.length
- secret and guess consist of digits only
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code