Bulls and Cows (LeetCode 299): Solution and Explanation

Medium
Hash Table
String
Counting

Compare a guess with a secret of the same length. Bulls are digits that match in value and position. Cows are digits that appear in the secret at another position, where each secret digit can be used only once. Return the hint as xAyB.

Intuition

Bulls are a direct position-by-position comparison. The tricky part is cows when digits repeat: with secret 1123 and guess 0111, the guess has three 1s, but after the bull at index 1 the secret has only one 1 left to pair with, so there is exactly one cow.

That suggests counting. Among non-bull positions, the cows contributed by digit d are min(unmatched secret copies of d, unmatched guess copies of d). A two-pass solution counts both sides and sums the minimums.

A single pass works with one array count[10] used as a balance. When a secret digit s is left unmatched, count[s] goes up. When a guess digit g is left unmatched, count[g] goes down. So a negative count[s] means guess copies of s are waiting for a partner, and a positive count[g] means secret copies of g are waiting.

At each non-bull position, the secret digit pairs with a waiting guess copy if one exists, and the guess digit pairs with a waiting secret copy if one exists. Each pairing is one cow, and the balance update consumes the copy that was used.

Approach: One pass with a balance array

  1. Set bulls = cows = 0 and count = [0] * 10.
  2. For each index i, read s = secret[i] and g = guess[i]. If they are equal, add a bull and move on.
  3. Otherwise, if count[s] < 0, a guess copy of s was waiting: add a cow. If count[g] > 0, a secret copy of g was waiting: add a cow.
  4. Then count[s] += 1 and count[g] -= 1.
  5. Return f"{bulls}A{cows}B".

Step-by-step example

secret = "1807", guess = "7810"
  1. i = 0: 1 vs 7 differ. Nothing is waiting, so count[1] becomes 1 and count[7] becomes -1.
  2. i = 1: 8 vs 8 match, a bull. bulls = 1.
  3. i = 2: 0 vs 1 differ. count[0] = 0, no cow from the secret side. count[1] = 1 > 0, so the guess 1 pairs with the waiting secret 1: cows = 1. Now count[0] = 1, count[1] = 0.
  4. i = 3: 7 vs 0 differ. count[7] = -1 < 0, so the secret 7 pairs with the waiting guess 7: cows = 2. count[0] = 1 > 0, so the guess 0 pairs with the waiting secret 0: cows = 3.
  5. Return 1A3B.

Code: Python, Java, C++

1class Solution:
2    def getHint(self, secret: str, guess: str) -> str:
3        bulls = 0
4        cows = 0
5        count = [0] * 10
6        for i in range(len(secret)):
7            s = int(secret[i])
8            g = int(guess[i])
9            if s == g:
10                bulls += 1
11            else:
12                if count[s] < 0:
13                    cows += 1
14                if count[g] > 0:
15                    cows += 1
16                count[s] += 1
17                count[g] -= 1
18        return f"{bulls}A{cows}B"
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each position is visited once and does a constant amount of work.

Space

O(1)

Only ten counters, independent of the input length. The output string has constant size for practical purposes.

Other approaches

Two passes with two count arrays (time O(n), space O(1))

First count bulls and, for non-bull positions, tally secret digits and guess digits separately. Then cows = sum over d of min(secretCount[d], guessCount[d]). It is easier to explain and equally fast.

Hash maps (time O(n), space O(1))

Same counting idea with dictionaries instead of arrays. It works for any alphabet, but ten digits fit naturally in an array.

Common mistakes

  • Counting a digit as a cow when it is already a bull. Bull positions must be excluded from the cow tallies.
  • Counting the same secret digit for several guess digits. With duplicates, cows for a digit are the minimum of the two unmatched counts, not the guess count.
  • Checking count[g] > 0 after updating count[s] when s == g is impossible here because equal digits are bulls, but in the two-array version, mixing up which side each update touches leads to wrong totals.
  • Formatting the result as 1A 3B or A1B3. The exact format is bulls, A, cows, B.

Frequently asked questions

Why can one array track both sides?

At any moment, for each digit only one side can have unmatched copies waiting: if both had one, they would already have been paired into a cow. So the sign of count[d] says which side is waiting and its magnitude says how many.

Can a position contribute two cows?

Yes. Its secret digit can pair with an earlier guess digit, and its guess digit can pair with an earlier secret digit. In the example, index 3 does exactly that.

Is the two-pass solution acceptable in an interview?

Yes. It has the same complexity. The one-pass balance array is a nice follow-up that shows you can merge the two tallies.