Python 0299.py
class Solution:
def getHint(self, secret: str, guess: str) -> str:
sec = [ c for c in secret ] # strings are immutable => convert to lists
gue = [ c for c in guess ]
size = len(sec)
bulls = 0
for i in range(size):
if sec[i] == gue[i]:
bulls += 1
# invalidate digits
sec[i] = "x"
gue[i] = "o"
freqSec = defaultdict(int)
for c in sec:
freqSec[c] += 1
cows = 0
for c in gue:
if freqSec[c] > 0:
freqSec[c] -= 1
cows += 1
return str(bulls) + "A" + str(cows) + "B"
Difficulty
and has an acceptance rate of about 53% (800k+ submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “Bulls and Cows” hint generation problem. It receives two equal-length strings, secret and guess, and returns a formatted hint indicating how many characters are correct in both value and position (bulls) and how many are correct in value but placed in a different position (cows). The algorithm proceeds in two distinct phases: first it identifies exact matches, then it counts value-only matches using a frequency table.
Key Steps
Convert immutable strings to mutable lists
sec = [c for c in secret] # strings are immutable => convert to lists
gue = [c for c in guess]
size = len(sec)
By turning the input strings into lists, the code can overwrite matched positions later, avoiding the need for auxiliary boolean arrays.
First pass - count bulls and invalidate matched positions
bulls = 0
for i in range(size):
if sec[i] == gue[i]:
bulls += 1
# invalidate digits
sec[i] = "x"
gue[i] = "o"
During this linear scan each index is examined once. When a bull is found, the corresponding entries in both sec and gue are replaced with sentinel characters ("x" and "o"). This prevents those characters from being considered in the subsequent cow counting phase.
Build a frequency map of the remaining secret characters
freqSec = defaultdict(int)
for c in sec:
freqSec[c] += 1
A defaultdict automatically supplies a zero count for unseen keys, simplifying the update logic. The map records how many times each non-bull character appears in the secret after the first pass.
Second pass - count cows using the frequency map
cows = 0
for c in gue:
if freqSec[c] > 0:
freqSec[c] -= 1
cows += 1
Each character from the modified guess list is checked against the frequency table. If the character is still available (count > 0), it contributes to the cow count and the table entry is decremented, ensuring that each secret character participates in at most one cow match.
Assemble the final hint string
return str(bulls) + "A" + str(cows) + "B"
The result follows the required “xAyB” format, concatenating the numeric counts with the literal letters.
Edge Cases Handled
When the two strings are empty, the list conversion yields empty lists, the loops execute zero iterations, and the function correctly returns "0A0B".
If every character matches in both value and position, the first pass marks all entries as bulls, replaces every element with the sentinel values, and the frequency map ends up containing only the sentinel key. The second pass finds no remaining matches, resulting in a cow count of zero.
When the strings contain repeated characters, the frequency map accurately tracks the remaining occurrences after bulls are removed. The decrement operation in the cow-counting loop guarantees that a secret character is paired with at most one guess character, preventing over-counting in scenarios such as secret = "1122" and guess = "2211".
The use of defaultdict ensures that lookups for characters that never appear in the secret (including the sentinel values) safely return zero, so the condition freqSec[c] > 0 never raises a KeyError.
Performance Optimizations
The algorithm avoids nested iteration by separating the work into two linear passes. The first pass simultaneously identifies bulls and marks them, eliminating the need for a separate data structure to remember matched indices.
Mutating the list representations in place removes the overhead of constructing additional collections for tracking used positions.
Employing a hash-based frequency table (defaultdict) provides constant-time updates and lookups for character counts, which is more efficient than scanning the list repeatedly to find matches.
By decrementing the frequency count as soon as a cow is recorded, the code prevents later iterations from revisiting already paired characters, ensuring that each element contributes to at most one cow calculation.
Overall, the design achieves a single-pass identification of exact matches followed by a single-pass aggregation of value-only matches, delivering a streamlined and cache-friendly execution flow.
ELI5 - Simplified Explanation
Imagine there is a secret number code and someone tries to guess it. This code acts like a helper who looks at both the secret code and the guest's guess to see how close they got to winning.
First, the code takes the secret numbers and the guess and lays them out like a row of colored blocks so they are easier to handle. Then, it walks down the line from the very first block to the last one. If a block in the guess matches the block in the secret exactly, they are perfect matches. When a perfect match is found, the code marks those blocks off the list so they do not get counted ever again, and it keeps a tally of these perfect matches.
After checking for those perfect matches, the code looks at whatever is left. It counts how many of each color are still hidden in the secret code. Then, it looks at the remaining guess blocks one by one. If one of these remaining guess blocks is also hiding somewhere else in the secret list, the code counts that as a near miss. It keeps a tally of these near misses as it goes along. Finally, the code puts together the number of perfect matches and the number of near misses to show how good the guess was.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | Java | Go | PHP | TS | |||||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | aylei | Rust | |||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| aylei | Rust | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| suxrobGM | C# | ||||||||||||
| trung-hn | Python | ||||||||||||
| varunu28 | Java | ||||||||||||
| vthwang | Java | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 401: Binary Watch
- problem 227: Basic Calculator II
- problem 241: Different Ways to Add Parentheses
- problem 284: Peeking Iterator
- problem 365: Water and Jug Problem
- problem 375: Guess Number Higher or Lower II
- problem 376: Wiggle Subsequence
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality