Bulls and Cows

Medium Hash Maps

Problem

Given two strings secret and guess, return a hint string that indicates how many digits in guess match the digits in secret exactly in both digit and position (bulls) and how many digits match the secret but are in the wrong position (cows).

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

Example

Input: secret = "1807", guess = "7810"
Output: "1A3B"

The algorithm iterates through each position comparing digits. At index 0, secret has '1' and guess has '7' — no exact match, so counts for '1' and '7' are recorded. At index 1, secret has '8' and guess has '8' — an exact match (bull), so bulls increment to 1. At index 2, secret has '0' and guess has '1' — no exact match, counts recorded. At index 3, secret has '7' and guess has '0' — no exact match, counts recorded. After this pass, bulls = 1. The unmatched digits are tallied in two hash maps for secret and guess respectively.

Approach

Straightforward Solution

A naive approach would compare every digit in guess against every digit in secret to count cows, resulting in O(n²) time complexity, which is inefficient for longer strings.

Core Observation

Exact matches (bulls) are straightforward to count by comparing characters at the same index. However, counting cows requires tracking unmatched digits separately because they must be matched across positions without double counting.

Path to Optimal

The key insight is to separate bulls from cows by first counting exact matches and then using hash maps to count frequencies of unmatched digits in both strings. The number of cows for each digit is the minimum count of that digit in secret and guess unmatched sets. This reduces the problem to O(n) time with O(1) space since digits are limited to 0-9.

Optimal Approach

Iterate once through both strings simultaneously. For each index, if digits match, increment bulls. Otherwise, increment counts in secret_counts and guess_counts hash maps. After the iteration, sum the minimum counts for each digit in guess_counts against secret_counts to get cows. Return the formatted string combining bulls and cows.

Time

O(n)

The solution iterates through the strings once to count bulls and build frequency maps, then iterates through the keys of guess_counts (at most 10 digits) to compute cows, resulting in linear time relative to input length.

Space

O(1)

The hash maps store counts for digits 0-9 only, so space usage is constant and does not scale with input size.

Pattern Spotlight

Hash Maps (Frequency Counting with Complement Matching)

Separate exact matches from partial matches by first identifying and excluding exact matches, then use frequency maps to count how many unmatched digits overlap, ensuring no double counting.

Solution

1class Solution:
2 def getHint(self, secret: str, guess: str) -> str:
3 bulls = 0
4 secret_counts = {}
5 guess_counts = {}
6
7 for index in range(len(secret)):
8 secret_digit = secret[index]
9 guess_digit = guess[index]
10
11 if secret_digit == guess_digit:
12 bulls += 1
13 else:
14 secret_counts[secret_digit] = secret_counts.get(secret_digit, 0) + 1
15 guess_counts[guess_digit] = guess_counts.get(guess_digit, 0) + 1
16
17 cows = 0
18
19 for digit in guess_counts:
20 cows += min(guess_counts[digit], secret_counts.get(digit, 0))
21
22 return str(bulls) + "A" + str(cows) + "B"

Step-by-Step Solution

1

Count Bulls and Build Frequency Maps for Unmatched Digits

3bulls = 0
4secret_counts = {}
5guess_counts = {}
7for index in range(len(secret)):
8 secret_digit = secret[index]
9 guess_digit = guess[index]
11 if secret_digit == guess_digit:
12 bulls += 1
14 secret_counts[secret_digit] = secret_counts.get(secret_digit, 0) + 1
15 guess_counts[guess_digit] = guess_counts.get(guess_digit, 0) + 1

Objective

To identify exact matches and simultaneously record the frequency of unmatched digits in both secret and guess.

Key Insight

By iterating once over both strings, the algorithm efficiently separates bulls from potential cows. Exact matches are counted immediately, while unmatched digits are recorded in hash maps. This separation is crucial because it prevents double counting and sets up a simple frequency comparison to find cows.

Interview Quick-Check

Core Logic

Increment bulls when digits match at the same index; otherwise, increment counts in secret_counts and guess_counts for unmatched digits.

State & Boundaries

Iterate over the entire length of the strings, ensuring all positions are checked exactly once.

Common Pitfalls & Bugs

Failing to separate bulls before counting frequencies leads to incorrect cow counts due to double counting exact matches.

2

Calculate Cows by Summing Minimum Frequency Overlaps

17cows = 0
19for digit in guess_counts:
20 cows += min(guess_counts[digit], secret_counts.get(digit, 0))

Objective

To compute the number of cows by summing the minimum counts of each digit present in both secret and guess unmatched frequency maps.

Key Insight

Since cows represent digits present in both strings but in different positions, the count for each digit is limited by the smaller frequency between secret and guess unmatched digits. Summing these minimums across all digits yields the total cows count without double counting.

Interview Quick-Check

Core Logic

For each digit in guess_counts, add the minimum of its count in guess_counts and secret_counts to cows.

State & Boundaries

Only digits present in guess_counts need to be checked, as digits absent in guess cannot contribute to cows.

Common Pitfalls & Bugs

Not using the minimum frequency leads to overcounting cows when one string has more occurrences of a digit than the other.

3

Format and Return the Final Hint String

22return str(bulls) + "A" + str(cows) + "B"

Objective

To construct the output string in the format 'xAyB' where x is bulls and y is cows.

Key Insight

The problem requires a specific output format combining bulls and cows counts. Concatenating the counts with 'A' and 'B' respectively produces the required hint string.

Interview Quick-Check

Core Logic

Return the string combining bulls and cows counts with 'A' and 'B' as separators.

Line Analysis

This solution has 2 Critical lines interviewers watch for.

Line 11 Critical
if secret_digit == guess_digit:

Check if the secret and guess digits match exactly at this position.

This check is the critical decision point that separates bulls from cows, ensuring exact matches are counted immediately and excluded from frequency maps.

Line 20 Critical
cows += min(guess_counts[digit], secret_counts.get(digit, 0))

Add the minimum frequency of the digit between guess and secret unmatched counts to cows.

This line embodies the core logic for counting cows by matching frequencies of unmatched digits, preventing double counting and ensuring correctness.

Line 4 Core
secret_counts = {}

Initialize a hash map to count unmatched digits in secret.

This map stores frequencies of digits in secret that do not match guess at the same position, enabling later calculation of cows.

Line 5 Core
guess_counts = {}

Initialize a hash map to count unmatched digits in guess.

This map stores frequencies of digits in guess that do not match secret at the same position, enabling later calculation of cows.

Line 14 Core
secret_counts[secret_digit] = secret_counts.get(secret_digit, 0) + 1

Increment frequency count for unmatched secret digit.

Recording unmatched secret digits allows later comparison with guess digits to identify cows without double counting bulls.

Line 15 Core
guess_counts[guess_digit] = guess_counts.get(guess_digit, 0) + 1

Increment frequency count for unmatched guess digit.

Recording unmatched guess digits enables calculation of cows by comparing frequencies with secret unmatched digits.

Line 3 Core
bulls = 0

Initialize bulls count to zero.

This variable tracks the number of digits that match exactly in both value and position, which is the primary metric for bulls.

Line 12 Core
bulls += 1

Increment bulls count for an exact match.

Incrementing bulls here ensures accurate counting of digits matched in both value and position, which is essential for the final hint.

Line 19 Core
for digit in guess_counts:

Iterate over each digit recorded in guess unmatched counts.

Checking only digits present in guess unmatched counts optimizes the calculation of cows by focusing on relevant digits.

Line 22 Core
return str(bulls) + "A" + str(cows) + "B"

Return the formatted hint string combining bulls and cows counts.

Constructing the output string in the required format completes the problem's specification and delivers the final answer.

Line 7 Standard
for index in range(len(secret)):

Iterate over each index of the input strings.

A single pass over the strings ensures all positions are checked for exact matches and unmatched digits efficiently.

Line 17 Standard
cows = 0

Initialize cows count to zero.

This variable accumulates the count of digits that match in value but not in position, completing the hint calculation.

Line 8 Standard
secret_digit = secret[index]

Retrieve the digit from secret at the current index.

Accessing the current secret digit is necessary to compare with the guess digit for bulls and to update frequency counts if unmatched.

Line 9 Standard
guess_digit = guess[index]

Retrieve the digit from guess at the current index.

Accessing the current guess digit is necessary for comparison and frequency counting.

Test Your Understanding

Why must bulls be counted separately before counting cows using frequency maps?

Because bulls represent digits matched exactly in position and must be excluded from frequency counts to avoid double counting them as cows, which represent digits matched in value but in different positions.

Related Problems

Hash Maps pattern

Don't just read it. Drill it.

Reconstruct Bulls and Cows from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Bulls and Cows drill

or drill a free problem