Problem 299

Abstract / Summary

Guess a secret number based on hints about how many digits match exactly and how many are correct but in wrong positions.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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"
25 lines | 705 bytes | submitted September 8, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (800k+ submissions).

Typical patterns to solve this problem:
  • Counting
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.88 | σ = 0.85

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
42 links | 28 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'bulls and cows | bulls and cows leetcode | leetcode 299 | string'
Naresh Gupta 10 mins
bulls and cows | bulls and cows leetcode | leetcode 299 | string
YouTube video 'Bulls and Cows | Leet code 299 | Theory explained + Python code'
Sai Anish Malla 14 mins
Bulls and Cows | Leet code 299 | Theory explained + Python code
YouTube video 'Bulls And Cows Leetcode | Leetcode 299 | Leetcode September Challenge'
Code Bashers 13 mins
Bulls And Cows Leetcode | Leetcode 299 | Leetcode September Challenge
YouTube video 'Leetcode - Bulls and Cows (Python)'
Timothy H Chang 6 mins
Leetcode - Bulls and Cows (Python)
YouTube video 'Bulls and Cows - LeetCode September Challenge Week 2.3'
Code for Cause 8 mins
Bulls and Cows - LeetCode September Challenge Week 2.3
YouTube video 'Bulls and Cows | Leetcode September Challenge Day10 Leetcode 299'
Coding Decoded 8 mins
Bulls and Cows | Leetcode September Challenge Day10 Leetcode 299
YouTube video '299. Bulls and Cows | LEETCODE MEDIUM'
code Explainer 5 mins
299. Bulls and Cows | LEETCODE MEDIUM
YouTube video 'LeetCode 299: Bulls and Cows - Detailed Explanation and Solution (Python)'
Cameron Porteous 12 mins
LeetCode 299: Bulls and Cows - Detailed Explanation and Solution (Python)
YouTube video 'LeetCode 299 : Bulls and Cows | C++ | Algo Master Sheet'
Wingineers 15 mins
LeetCode 299 : Bulls and Cows | C++ | Algo Master Sheet
YouTube video 'Bulls and Cows LeetCode September Challenge'
SM TechWorld 13 mins
Bulls and Cows LeetCode September Challenge
YouTube video 'Daily Leetcode #163: Sep 10, 2020 - 299. Bulls and Cows'
Programming Live with Larry 7 mins
Daily Leetcode #163: Sep 10, 2020 - 299. Bulls and Cows
YouTube video 'LeetCode 299 | Bulls and Cows | Counting | Java'
Sleepy Cracker 9 mins
LeetCode 299 | Bulls and Cows | Counting | Java
YouTube video 'ByteDance Coding Interview Question | Leetcode 299 | Bulls and Cows'
WorkWithGoogler 19 mins
ByteDance Coding Interview Question | Leetcode 299 | Bulls and Cows
YouTube video 'Bulls and Cows | September Leetcode Challenge | Leetcode 299| Day 10'
Ayushi Rawat 7 mins
Bulls and Cows | September Leetcode Challenge | Leetcode 299| Day 10
YouTube video '[LeetCode] 299. Bulls and Cows || [CtCI] 16.15 Master Mind || HashTable || Java'
Riyafa Abdul Hameed 21 mins
[LeetCode] 299. Bulls and Cows || [CtCI] 16.15 Master Mind || HashTable || Java
YouTube video '299 -  bulls and cows - leetcode'
eli5leetcode - "Explain Like I'm 5 years old" 9 mins
299 - bulls and cows - leetcode
YouTube video 'Bulls and Cows Game - LeetCode Solution & Algorithm Explained'
CodeLucky 4 mins
Bulls and Cows Game - LeetCode Solution & Algorithm Explained
YouTube video 'Leetcode Question 299 "Bulls and Cows" in Java'
Ghumman Tech 7 mins
Leetcode Question 299 "Bulls and Cows" in Java
YouTube video 'Bulls and Cows (Medium), C++, Leetcode'
H William Polenz 25 mins
Bulls and Cows (Medium), C++, Leetcode
YouTube video 'Bulls and Cows - LeetCode 299 - Swift'
CodeMaster Quest 7 mins
Bulls and Cows - LeetCode 299 - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 6 medium
8 solutions   September 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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