DDSA Solutions

299. Bulls and Cows

Time: O(n)
Space: O(1)
Advertisement

Intuition

Bulls: count exact position matches in one pass. Cows: count non-bull digits in secret that appear as non-bull digits in guess. Use two frequency arrays for digits 0 - 9.

Algorithm

  1. 1For each position i: if secret[i]==guess[i], bulls++. Else: sCount[secret[i]]++, gCount[guess[i]]++.
  2. 2cows = sum over 0 - 9 of min(sCount[d], gCount[d]).
  3. 3Return "{bulls}A{cows}B".

Example Walkthrough

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

  1. 1.Position 1: "8"=="8" -> bulls=1. Others: sCount[1,0,7]++, gCount[7,1,0]++.
  2. 2.cows: min(1,1)+min(1,1)+min(1,1)=3.

Output: "1A3B"

Common Pitfalls

  • Count non-bull occurrences only - do not double-count bull positions in the cow calculation.
299.cs
C#
// Approach: Count exact-position matches (bulls) first; count digit frequency
// overlap in non-matching positions for cows.
// Time: O(n) Space: O(1)

public class Solution
{
    public string GetHint(string secret, string guess)
    {
        int A = 0;
        int B = 0;
        int[] count1 = new int[10];
        int[] count2 = new int[10];

        for (int i = 0; i < secret.Length; ++i)
        {
            if (secret[i] == guess[i])
                ++A;
            else
            {
                ++count1[secret[i] - '0'];
                ++count2[guess[i] - '0'];
            }
        }

        for (int i = 0; i < 10; ++i)
            B += Math.Min(count1[i], count2[i]);

        return $"{A}A{B}B";
    }
}
Advertisement
Was this solution helpful?