LeetCode Problem

How to Solve Bulls and Cows

Bulls and Cows involves comparing a secret number with a guess and providing a hint based on exact matches and misplaced digits. By using hash tables, we can efficiently count and compare digit occurrences to generate the hint in 'A' for exact matches and 'B' for misplaced ones. Optimizing this comparison can significantly reduce unnecessary operations and improve performance in large inputs.

GhostInterview Help

Need help with Bulls and Cows without spending extra time grinding it?

GhostInterview can read Bulls and Cows from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #299Hash Table plus StringReviewed 2026-03-08
Difficulty
Medium
Primary pattern
Hash Table plus String
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

Bulls and Cows involves comparing a secret number with a guess and providing a hint based on exact matches and misplaced digits. By using hash tables, we can efficiently count and compare digit occurrences to generate the hint in 'A' for exact matches and 'B' for misplaced ones. Optimizing this comparison can significantly reduce unnecessary operations and improve performance in large inputs.

Problem Statement

You are playing a game with a secret number and your friend’s guess. The goal is to provide feedback about how close the guess is to the secret number. The feedback should consist of two numbers: the number of bulls and the number of cows. A bull is a digit that is in the correct position, while a cow is a digit that exists in the secret but is in the wrong position.

Given two strings, secret and guess, both representing the secret number and the guessed number respectively, return a string hint of the form 'xAyB', where 'x' is the number of bulls and 'y' is the number of cows. You need to consider digits that appear in both secret and guess, ensuring efficient counting of misplaced digits.

Examples

Example 1

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Bulls are connected with a '|' and cows are underlined: "1807" | "7810"

Example 2

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Bulls are connected with a '|' and cows are underlined: "1123" "1123" | or | "0111" "0111" Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.

Constraints

  • 1 <= secret.length, guess.length <= 1000
  • secret.length == guess.length
  • secret and guess consist of digits only.

Solution Approach

Count Exact Matches (Bulls)

First, iterate through both secret and guess strings. For each digit that matches at the same index, increase the bull count. This step is straightforward and provides a direct way to track exact matches.

Count Misplaced Digits (Cows)

After counting the bulls, a hash table can be used to count the frequency of unmatched digits in both secret and guess. For each unmatched digit in guess, check if it exists in the hash table of secret and count it as a cow if it does. This allows for an efficient count of misplaced digits.

Edge Case Handling

Make sure to handle edge cases like when secret and guess contain the same repeated digits. For example, '1122' and '2211' should be carefully processed to ensure only the correct number of cows are counted, without overcounting any digits.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

The time complexity is O(n), where n is the length of the strings secret and guess, because we are iterating through the strings to count bulls and cows. The space complexity is O(1) in terms of extra space, assuming the hash table for counting digit frequencies uses a fixed-size array for digits 0-9.

What Interviewers Usually Probe

  • Does the candidate consider both bulls and cows efficiently?
  • How well does the candidate handle edge cases like repeated digits in both secret and guess?
  • Can the candidate discuss time and space complexities clearly in relation to hash tables?

Common Pitfalls or Variants

Common pitfalls

  • Failing to properly account for repeated digits can lead to incorrect cow counts.
  • Using a brute force approach for comparing all digits without using a hash table can significantly increase time complexity.
  • Not handling edge cases like when all digits are bulls or cows could result in missed cases.

Follow-up variants

  • Consider a version where the strings have different lengths, adding a validation step before proceeding.
  • Modify the problem to work with non-digit strings, such as alphanumeric characters.
  • Incorporate a timing constraint to optimize the solution's performance under time limits.

How GhostInterview Helps

  • GhostInterview helps by providing step-by-step insights into efficient approaches to solve Bulls and Cows using hash tables and string manipulation.
  • It guides you in identifying common pitfalls and understanding their impact on algorithmic performance in real interview scenarios.
  • The platform also gives instant feedback on time and space complexity, ensuring your solution is both optimal and scalable.

Topic Pages

FAQ

What is the core approach to solving the Bulls and Cows problem?

The core approach to solving Bulls and Cows is using hash tables to efficiently count and match digits in both the secret and guess strings.

How do bulls and cows differ in the context of this problem?

Bulls are digits that match both in value and position between the secret and guess, while cows are digits that match in value but are in the wrong position.

Why is using a hash table critical in this problem?

A hash table allows for efficient counting of digit frequencies, which is essential for accurately counting cows while keeping the time complexity manageable.

How do you handle repeated digits when calculating cows?

When handling repeated digits, ensure that cows are counted only for unmatched digits that are available in the secret. Be mindful of the number of occurrences in both strings to avoid overcounting.

What is the expected time complexity for solving Bulls and Cows?

The expected time complexity is O(n), where n is the length of the strings, as we process each character once to count bulls and cows.

GhostInterview Solver

Need direct help with Bulls and Cows instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Bulls and Cows from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.